0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlinと図で学んでみるデザインパターン -3章 Template Methodパターン-

Last updated at Posted at 2019-09-17

Template Methodパターン

親クラスで処理の枠組みを決め、サブクラスに実装を任せる
Untitled Diagram.png

abstract class AbstractDisplay {
    abstract fun open()
    abstract fun print()
    abstract fun close()
    fun display() {
        open()
        repeat(5) {
            print()
        }
        close()
    }
}
class CharDisplay(private val ch: CharSequence) : AbstractDisplay() {
    override fun open() {
        print("<<")
    }

    override fun print() {
        print(ch)
    }

    override fun close() {
        println(">>")
    }
}
class StringDisplay(private val string: String) : AbstractDisplay() {

    private val width : Int = string.toByteArray().size

    override fun open() {
        printLine()
    }

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

    override fun close() {
        printLine()
    }

    private fun printLine(){
        print("+")
        repeat(width){
            print("-")
        }
        println("+")
    }
}
fun main(){
    val d1 : AbstractDisplay = CharDisplay("h")
    val d2 : AbstractDisplay = StringDisplay("Hello World")
    val d3 : AbstractDisplay = StringDisplay("こんにちは。")

    d1.display()
    d2.display()
    d3.display()
}

※ Java 言語で学ぶデザインパターン入門をKotlinと図で理解しようとしている学習用アウトプットです。UML書式に沿ってはいません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?