本篇继续练习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()
}
输出: