げんとめブログ

State:kotlin

気を付けたこと


import java.awt.*
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import kotlin.system.exitProcess

fun main(args: Array<String>) {
    val frame = SafeFrame("State Sample")
    while (true) {
        for (hour in 0 until 24) {
            frame.setClock(hour)
            try {
                Thread.sleep(1000)
            } catch (e: InterruptedException) {

            }
        }
    }
}
class DayState private constructor() : State {
    companion object {
        private val singleton = DayState()
        fun getInstance() = singleton
    }

    override fun doCLock(context: Context,hour:Int) {
        if (hour < 9 || 17 <= hour) {
            context.changeState(NightState.getInstance())
        }
    }

    override fun doUse(context: Context) {
        context.recordLog("金子使用(昼間)")
    }

    override fun doAlarm(context: Context) {
        context.callSecurityCenter("非常ベル(昼間)")
    }

    override fun doPhone(context: Context) {
        context.callSecurityCenter("通常の通話(昼間)")
    }

    override fun toString(): String {
        return "[昼間]"
    }

}
class NightState private constructor(): State {
    companion object {
        private val singleton = NightState()
        fun getInstance() = singleton
    }

    override fun doCLock(context: Context, hour: Int) {
        if (9 <= hour && hour < 17) {
            context.changeState(DayState.getInstance())
        }

    }

    override fun doUse(context: Context) {
        context.callSecurityCenter("非常:夜間の禁固しよう")
    }

    override fun doAlarm(context: Context) {
        context.callSecurityCenter("非常ベル(夜間)")
    }

    override fun doPhone(context: Context) {
        context.recordLog("夜間の通話録音")
    }

    override fun toString(): String {
        return "「夜間」"
    }
}
class SafeFrame(title:String) : Frame(title), ActionListener, Context {
    private val textClock = TextField(60)
    private val textScreen = TextArea(10, 60)
    private val buttonUse = Button("金庫使用")
    private val buttonAlarm = Button("非常ベル")
    private val buttonPhone = Button("非常通話")
    private val buttonExit = Button("終了")
    private var state:State = DayState.getInstance()
    init {
        background = Color.lightGray
        layout = BorderLayout()
        add(textClock,BorderLayout.NORTH)
        textClock.isEditable = false
        add(textScreen, BorderLayout.CENTER)
        textScreen.isEditable = false
        val panel = Panel()
        panel.add(buttonUse)
        panel.add(buttonAlarm)
        panel.add(buttonPhone)
        panel.add(buttonExit)
        add(panel, BorderLayout.SOUTH)
        pack()
        show()
        buttonUse.addActionListener(this)
        buttonAlarm.addActionListener(this)
        buttonPhone.addActionListener(this)
        buttonExit.addActionListener(this)

    }

    override fun actionPerformed(e: ActionEvent) {
        println(e.toString())
        when (e.source) {
            buttonUse -> {
                state.doUse(this)
            }
            buttonAlarm -> state.doAlarm(this)
            buttonPhone -> state.doPhone(this)
            buttonExit -> exitProcess(0)
            else -> println("?")
        }

    }

    override fun setClock(hour: Int) {
        var clockstring = "現在時刻は"
        if (hour < 10) {
            clockstring += "0${hour}:00"
        } else {
            clockstring += "${hour}:00"
        }
        println(clockstring)
        textClock.text = clockstring
        state.doCLock(this,hour)
    }

    override fun changeState(state: State) {
        println("${this.state}から${state}へ状態が変化しました")
        this.state = state
    }

    override fun callSecurityCenter(msg: String) {
        textScreen.append("call! ${msg}\n")
    }

    override fun recordLog(msg: String) {
        textScreen.append("record ... ${msg}\n")
    }
}
interface State {
    abstract fun doCLock(context: Context,hour:Int)
    abstract fun doUse(context: Context)
    abstract fun doAlarm(context: Context)
    abstract fun doPhone(context: Context)
}
interface Context {
    abstract fun setClock(hour: Int)
    abstract fun changeState(state: State)
    abstract fun callSecurityCenter(msg: String)
    abstract fun recordLog(msg:String)
}

元のコードは以下の本からの引用です。サンプルコードは著者さんのサイトで配布されています。リンクはAmazonアソシエイトを使用しています。

増補改訂版Java言語で学ぶデザインパターン入門

ライセンス表記

Copyright (C) 2001,2004 Hiroshi Yuki.

『増補改訂版Java言語で学ぶデザインパターン入門』サポートページ
hyuki@hyuki.com
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution.
Exit mobile version