増補改訂版Java言語で学ぶデザインパターン入門のBridgeパターンをkotlinで書き直してみます。
気を付けたこと
- コンストラクタ内でフィールドの宣言と初期化する
- クラス宣言はdefaultでfinalなので、継承する場合はopen修飾子をつける
- javaではpublicなクラスは一つのファイルに一つだけにするべきというのがあったが、kotlinではその制限はないので一つのファイルにまとめた
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
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アソシエイトを使用しています。
ライセンス表記
Copyright (C) 2001,2004 Hiroshi Yuki.
hyuki@hyuki.com『増補改訂版Java言語で学ぶデザインパターン入門』サポートページ
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.