Observer:kotlin

気を付けたこと

  • kotlinでは一つのファイルに複数クラスを書けるのでまとめた
  • for分の書き方がちょっと違う

import kotlin.concurrent.thread
import kotlin.random.Random

fun main(args: Array<String>) {
    val generator = RandomNumberGenerator()
    val observer1 = DigitObserver()
    val observer2 = GraphObserver()
    generator.addObserver(observer1)
    generator.addObserver(observer2)
    generator.execute()
}
interface Observer {
    abstract fun update(generator:NumberGenerator)
}
abstract class NumberGenerator {
    private val observers = arrayListOf<Observer>()
    fun addObserver(observer: Observer) {
        observers.add(observer)
    }
    fun deleteObserver(observer: Observer) {
        observers.remove(observer)
    }
    fun notifyObservers() {
        val it = observers.iterator()
        while (it.hasNext()) {
            val o = it.next()
            o.update(this)
        }
    }
    abstract fun getNumber(): Int
    abstract fun execute()
}
class RandomNumberGenerator : NumberGenerator() {
    private var number:Int = 0
    private val random = Random(0)
    override fun getNumber(): Int {
        return number
    }

    override fun execute() {
        for (i in 0 until 20) {
            number = random.nextInt(50)
            notifyObservers()
        }
    }
}
class DigitObserver : Observer {
    override fun update(generator: NumberGenerator) {
        println("DigitObserver:${generator.getNumber()}")
        try {
            Thread.sleep(100)
        } catch (e: InterruptedException) {
        }
    }
}
class GraphObserver : Observer {
    override fun update(generator: NumberGenerator) {
        print("GraphObserver:")
        val count = generator.getNumber()
        for (i in 0 until count) {
            print("*")
        }
        println("");
        try{
            Thread.sleep(100)
        }catch (e:InterruptedException){}
    }
}

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

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

ライセンス表記

Copyright (C) 2001,2004 Hiroshi Yuki.

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.

コメント

タイトルとURLをコピーしました