工厂模式demo笔记"/>
kotlin 工厂模式demo笔记
1.单例工厂模式
interface Computer {val cpu: String
}class PC(override val cpu: String = "intel") : Computer
class Mobile(override val cpu: String = "gt") : Computer
enum class ComputerType {PC, Mobile
}object ComputerFactory {operator fun invoke(type: ComputerType): Computer {return when (type) {ComputerType.PC -> PC()ComputerType.Mobile -> Mobile()}}
}fun main() { val p = ComputerFactory(ComputerType.Mobile)println(p.cpu)}
2.伴生对象创建静态工厂方法Demo
interface Computer {val cpu: Stringcompanion object {operator fun invoke(type: ComputerType): Computer {return when (type) {ComputerType.PC -> PC()ComputerType.Mobile -> Mobile()}}}
}class PC(override val cpu: String = "intel") : Computer
class Mobile(override val cpu: String = "gt") : Computer
enum class ComputerType {PC, Mobile
}fun main() {println(Computer(ComputerType.PC).cpu)println(Computer(ComputerType.Mobile).cpu)}
在不指定伴生对象名字时,可通过Computer来调用其伴生对象中的方法
companion object Factory{operator fun invoke(type: ComputerType): Computer {return when (type) {ComputerType.PC -> PC()ComputerType.Mobile -> Mobile()}}}
两种调用都可以:
println(Computer(ComputerType.PC).cpu)println(Computer.Factory(ComputerType.Mobile).cpu)
3.扩展伴生对象方法
fun Computer.Factory.fromCpu(cpu: String): ComputerType? = when (cpu) {"intel" -> ComputerType.PC"gt" -> ComputerType.Mobileelse -> null
}
4.抽象工厂模式
interface Computer {val logo: String
}abstract class AbstractFactory {abstract fun produce(): Computercompanion object Factory {operator fun invoke(factory: AbstractFactory): AbstractFactory = factory}
}class Dell(override val logo: String = "DELL") : Computer
class Apple(override val logo: String = "APPLE") : Computerclass DellFactory : AbstractFactory() {override fun produce(): Computer {return Dell()}
}class AppleFactory : AbstractFactory() {override fun produce(): Computer {return Apple()}
}fun main() {val dell = AbstractFactory(DellFactory()).produce()println(dell.logo)
}
5.内联函数来改抽象工厂
/*** 定义一个计算机接口*/
interface Computer {val logo: String
}/*** 抽象工厂*/
abstract class AbstractFactory {abstract fun produce(): Computercompanion object Factory {//内联函数,具名化泛型参数类型inline operator fun <reified T : Computer> invoke(): AbstractFactory =when (T::class) {Dell::class -> DellFactory()Apple::class -> AppleFactory()else -> throw IllegalArgumentException()}}
}/*** 品牌计算机*/
class Dell(override val logo: String = "DELL") : Computer
class Apple(override val logo: String = "APPLE") : Computer/*** 品牌工厂*/
class DellFactory : AbstractFactory() {override fun produce(): Computer {return Dell()}
}class AppleFactory : AbstractFactory() {override fun produce(): Computer {return Apple()}
}fun main() {val dell = AbstractFactory<Apple>().produce()println(dell.logo)
}
代码修改自《Kotlin核心编程》
更多推荐
kotlin 工厂模式demo笔记
发布评论