内联函数简化抽象工厂
2019-09-30 本文已影响0人
bravelion
1.通过invoke用inline定义为内联函数,同时引入reified关键字,使用具体化参数类型的语法特性
2.实现
interface Computer
class Dell: Computer
class Asus: Computer
class Acer: Computer
class DellFactory : AbstractFactory(){
override fun produce() = Dell()
}
class AsusFactory : AbstractFactory(){
override fun produce(): Computer = Asus()
}
class AcerFactory : AbstractFactory(){
override fun produce(): Computer = Acer()
}
open abstract class AbstractFactory {
abstract fun produce(): Computer
companion object {
inline operator fun invoke(): AbstractFactory =
when (T::class) {
Dell::class -> DellFactory()
Asus::class -> AsusFactory()
Acer::class -> AcerFactory()
else ->throw IllegalArgumentException()
}
}
}
3.调用
val dellFactory = AbstractFactory<Dell>()
val dell = dellFactory.produce()
本文摘自《Kotlin核心编程》