げんとめブログ

Bridgeパターン:kotlin

増補改訂版Java言語で学ぶデザインパターン入門のBridgeパターンをkotlinで書き直してみます。

気を付けたこと

fun main() {
    val d1 = Display(StringDisplayImpl("Hello,Japan."))
    val d2 = CountDisplay(StringDisplayImpl("Hello,World"))
    val d3 = CountDisplay(StringDisplayImpl("Hello,Universe."))
    d1.display()
    d2.display()
    d3.display()
    d3.multiDisplay(5)
}
open class Display(private val impl: DisplayImpl){
    fun open(){impl.rawOpen()}
    fun print(){impl.rawPrint()}
    fun close(){impl.rawCLose()}
    fun display(){
        open()
        print()
        close()
    }

}
class CountDisplay(impl: DisplayImpl) : Display(impl) {
    fun multiDisplay(times:Int){
        open()
        for (i in 0..times) {
            print()
        }
        close()
    }
}
abstract class DisplayImpl{
    abstract fun rawOpen()
    abstract fun rawPrint()
    abstract fun rawCLose()
}
class StringDisplayImpl(private val string:String):DisplayImpl(){
    private val width = string.toByteArray().size
    override fun rawOpen() {
        printLine()
    }

    override fun rawPrint() {
        println("|${string}|")
    }

    override fun rawCLose() {
        printLine()
    }
    private fun printLine(){
        print("+")
        for (i in 0..width) {
            print("-")
        }
        println("+")
    }
}

元のコードは以下の本からの引用です。サンプルコードは著者さんのサイトで配布されています。リンクは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