1
1

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と図で学んでみるデザインパターン -4章 Factoryパターン-

Posted at

Factoryパターン

作り方をスーパークラスで定義し、インスタンスの作成をサブクラスに任せる
Untitled Diagram (1).png

抽象クラス群

package framework

abstract class Product {
    abstract fun use()
}

abstract class Factory {
    fun create(owner: String): Product {
        val p = createProduct(owner)
        registerProduct(p)
        return p
    }
    protected abstract fun createProduct(owner: String): Product
    protected abstract fun registerProduct(product: Product)
}

具体クラス群

package idcard
import framework.*

class IdCard(private val owner: String) : Product() {

    init {
        println("{$owner}のカードを作ります")
    }

    override fun use() {
        println("{$owner}のカードを使います")
    }

    fun getOwner(): String {
        return owner
    }
}

class IdCardFactory() : Factory() {

    private val owners: MutableList<String> = mutableListOf()

    override fun createProduct(owner: String): Product {
        return IdCard(owner)
    }

    override fun registerProduct(product: Product) {
        val idCard : IdCard = product as? IdCard ?: return
        owners.add(idCard.getOwner())
    }

    fun getOwners() : List<String>{
        return owners
    }
}

実行

fun main(){
    val factory = IdCardFactory()
    val card1 = factory.create("Tsutou")
    val card2 = factory.create("Hanako")
    val card3 = factory.create("Taro")

    card1.use()
    card2.use()
    card3.use()
}

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?