设计模式 学习笔记: 工厂模式

工厂模式就相当于日常生活中的去买东西,如我们需要去买一辆车,我们不需要去知道车是怎么生产的,我们只需要告诉卖车的我们需什么车,我们就能买这车辆车,工厂模式就是这样,工厂模式的优点是1:当我们想创建一个对象时,只需要知道名称就好了2:拓展性高,如果想增加一个产品,只要扩展一个工厂类就可以了3:屏蔽产品的具体实现,调用者只关心产品的接口。当然工厂模式也有其缺陷1:每一次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,同时也增加了系统类的依赖。

例:1.创建一个接口

interface Shape{
    fun draw()
}

2.创建接口的实体类

class Circle: Shape {
    override fun draw() {
        println("Circle")
    }
}
class Rectangle: Shape{
    override fun draw() {
        println("Rectangle")
    }
}

3.创建一个工厂,生成基于给定信息的实体类的对象

class ShapeFactory(){
    fun getShape(s: String): Shape{
        if (s == "Circle") return Circle()
        else if (s == "Rectangle") return  Rectangle()
        else return object : Shape{
            override fun draw() {
                println("null")
            }

        }
    }
}

4.使用该工厂,通过传递类型信息来获取实体类的对象

fun main(){
    val circle = ShapeFactory().getShape("Circle")
    circle.draw()
    val rectangle = ShapeFactory().getShape("Rectangle")
    rectangle.draw()
}

5.执行程序,输出结果

例2

interface Shape{
    fun draw()
    companion object Factory{
        operator fun invoke(S:ShapeType):Shape{
            return when(S){
                ShapeType.Rectangle -> return Rectangle()
                ShapeType.Circle -> return Circle()
            }
        }
    }
}
enum class ShapeType{
    Circle,Rectangle
}
class Rectangle: Shape{
    override fun draw() {
        println("Rectangle")
    }
}
class Circle: Shape{
    override fun draw() {
        println("Circle")
    }
}
fun main(){
    val a = Shape.Factory(ShapeType.Rectangle)
    a.draw()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值