Kotlin设计模式:工厂模式


本篇继续练习kotlin设计模式之工厂模式,Factory,这个模式许多第三方类库都在使用,但是对于一般简单的对象类型还是直接使用新建比较好。用工厂反而繁琐,多此一举。

上代码:很直观,就不多说了。

package KotlinMode

/**
 * 工厂模式
 */

interface Fruits {
    fun showName()
}

class Lemon(private val strType: String) : Fruits {
    override fun showName() {
        println("当前构建对象是:$strType")
    }
}
class Pear(private val strType: String) : Fruits by Lemon(strType)
class Watermelon(private val strType: String) : Fruits by Lemon(strType)

/**
 * 创建工厂
 */
class FruitsFactory {

    fun createType(type: String): Fruits? {
        return when (type) {
            "Pear" -> {
                Pear(type)
            }
            "Watermelon" -> {
                Watermelon(type)
            }
            "Lemon" -> {
                Lemon(type)
            }
            else -> null
        }
    }

}


fun main() {

    val lemon = FruitsFactory().createType("Lemon")
    lemon?.showName()
    val watermelon = FruitsFactory().createType("Watermelon")
    watermelon?.showName()
    val pear = FruitsFactory().createType("Pear")
    pear?.showName()


}

null

输出:

null


文章作者: 2winter
文章链接: https://2winter.com
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 2winter !
  目录