一、产品类
package com.study.simple_factory
interface IPhone {
fun call()
fun sendMsg()
fun playGame()
}
package com.study.simple_factory
class HuaWeiPhoneImpl : IPhone {
override fun call() {
println("华为手机打电话...")
}
override fun sendMsg() {
println("华为手机发短信...")
}
override fun playGame() {
println("华为手机玩游戏...")
}
}
package com.study.simple_factory
class MiPhoneImpl : IPhone {
override fun call() {
println("XiaoMi手机打电话...")
}
override fun sendMsg() {
println("XiaoMi手机发短信...")
}
override fun playGame() {
println("XiaoMi手机玩游戏...")
}
}
package com.study.simple_factory
class VivoPhoneImpl : IPhone {
override fun call() {
println("Vivo手机打电话...")
}
override fun sendMsg() {
println("Vivo手机发短信...")
}
override fun playGame() {
println("Vivo手机玩游戏...")
}
}
二、工厂类
package com.study.simple_factory
object PhoneFactory{
fun createPhone(phoneEnum: PhoneEnum) = when (phoneEnum) {
PhoneEnum.HUAWEI -> HuaWeiPhoneImpl()
PhoneEnum.VIVO -> VivoPhoneImpl()
PhoneEnum.MI -> MiPhoneImpl()
}
}
三、主程序调用
package com.study.simple_factory
fun main(args: Array<String>) {
val miPhone = PhoneFactory.createPhone(PhoneEnum.MI)
val vivoPhone = PhoneFactory.createPhone(PhoneEnum.VIVO)
val huaweiPhone = PhoneFactory.createPhone(PhoneEnum.HUAWEI)
miPhone.call()
vivoPhone.call()
huaweiPhone.call()
}
四、运行结果