python实现设计模式(一、工厂模式)

学习版本3.5.2

1.简单工厂

有一个工厂存在两个流水线,A流水线生产A零件,B流水线生产B零件,需要A零件的时候跟工厂说生产A零件,需要B零件的时候跟工厂说生产B零件。

class ProductionLine(object):
    pass

class ProductionLineA(ProductionLine):
    def create(self):
        print("create componentA")

class ProductionLineB(ProductionLine):
    def create(self):
        print("create componentB")

class Factory(object):
    def create(self,type):
        if type == 'A':
            ProductionLineA().create()
        elif type == 'B':
            ProductionLineB().create()

if __name__ == '__main__':
    f = Factory()
    f.create('A')
    f.create('B')

运行结果

create componentA
create componentB

2.工厂方法

该工厂效益不错,需要扩大流水线的规模,所以把原来的工厂里面全部布置为A流水线并改名为A工厂,把B流水线搬出来并且建立一个新的工厂。当你需要A零件的时候叫A工厂生产零件,需要B零件的时候叫B工厂生产零件。

class ProductionLine(object):
    pass

class ProductionLineA(ProductionLine):
    def create(self):
        print("create componentA")

class ProductionLineB(ProductionLine):
    def create(self):
        print("create componentB")

class Factory(object):
    def create(self,type):
        pass

class FactoryA(Factory):
    def create(self):
        ProductionLineA().create()

class FactoryB(Factory):
    def create(self):
        ProductionLineB().create()

if __name__ == '__main__':
    f = FactoryA()
    f.create()
    f = FactoryB()
    f.create()

运行结果

create componentA
create componentB

3.抽象工厂

工厂的老板觉得还需要扩大业务,不再只单独生产零件了,自己去组装产品。原来的A零件和B零件能组成产品1.0,技术部改革了技术流水线能去生产性能更高的A2零件和B2零件,它们能组成产品2.0,1.0和2.0产品都是有市场的。所以老板去设定了1.0产品的工厂和2.0产品的工厂,两个工厂里都有AB两个流水线,只是技术员不一样。

class ProductionLine(object):
    pass

class ProductionLineA(ProductionLine):
    def create(self):
        "create componentA1"
        pass

class ProductionLineA2(ProductionLineA):
    def create(self):
        "create componentA2"
        pass

class ProductionLineB(ProductionLine):
    def create(self):
        "create componentB1"
        pass

class ProductionLineB2(ProductionLineB):
    def create(self):
        "create componentB2"
        pass

class Factory(object):
    def create(self,type):
        pass

class Factory1(Factory):
    def create(self):
        ProductionLineA().create()
        ProductionLineB().create()
        print("create product1.0")

class Factory2(Factory):
    def create(self):
        ProductionLineA2().create()
        ProductionLineB2().create()
        print("create product2.0")

if __name__ == '__main__':
    f = Factory1()
    f.create()
    f = Factory2()
    f.create()

运行结果

create product1.0
create product2.0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值