LoginSignup
1
0

More than 3 years have passed since last update.

Kotlinと図で学んでみるデザインパターン -6章 Prototypeパターン-

Last updated at Posted at 2020-03-17

Prototypeパターン

prototype == 原型/模範

abstract class Product : Cloneable {
    abstract fun use(s: String)
    fun createClone(): Product {
        var p: Product? = null
        try {
            p = clone() as Product
        } catch (e: CloneNotSupportedException) {
            e.printStackTrace()
        }
        return requireNotNull(p, { "product must not be null" })
    }
}
class Manager {
    private val showCase = hashMapOf<String, Product>()

    fun register(name: String, product: Product) {
        showCase[name] = product
    }

    fun create(photoName: String): Product {
        val p = showCase[photoName] as Product
        return p.createClone()
    }
}
class MessageBox(private var decoChar: String) : Product() {
    override fun use(s: String) {
        val length = s.toByteArray().size
        repeat(length + 3) {
            print(decoChar)
        }
        println("")
        println("""$decoChar $s $decoChar""")
        repeat(length + 3) {
            print(decoChar)
        }
        println("")
    }
}

class UnderLinePen(private var ulchar: String) : Product() {
    override fun use(s: String) {
        val length = s.toByteArray().size
        println("¥\"" + s + "¥\"")
        print(" ")
        repeat(length - 1) {
            print(ulchar)
        }
        println("")
    }
}
fun main() {
    val manager = Manager()
    val upen = UnderLinePen("~")
    val mbox = MessageBox("*")
    val sbox = MessageBox("/")

    manager.run {
        register("strong message", upen)
        register("warning box", mbox)
        register("slash box", sbox)
        create("strong message").use("Hello World")
        create("warning box").use("Hello World")
        create("slash box").use("Hello World")
    }
}

MEMO

データクラス - Kotlin Programming Language コピー

1
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
1
0