python 设计模式-工厂方法模式

前面我们介绍了简单工厂模式,每次添加新的产品需要对工厂代码进行相应修改,后面我们对它进行了一系列的优化,到最后把只需要对新建工厂时的参数进行调整就OK了。这里进一步对工厂的另一种形式进行介绍,工厂方法不仅对产品进行了抽象,对生产产品的工厂也进行了抽象,这样新加产品后只要新建相应的工厂就行,更符合面向对象的开闭原则。

示例代码如下:

from abc import ABCMeta, abstractmethod


class Product(metaclass=ABCMeta):
    pass


class Factory(metaclass=ABCMeta):
    @abstractmethod
    def produce(self):
        pass


class ProductA(Product):
    pass


class ProductB(Product):
    pass


class ProductAFactory(Factory):
    def produce(self):
        return ProductA()


class ProductBFactory(Factory):
    def produce(self):
        return ProductB()


if __name__ == '__main__':
    paf = ProductAFactory()
    pbf = ProductBFactory()
    a = paf.produce()
    b = pbf.produce()
    print(a, b)

输出:

<__main__.ProductA object at 0x03968810> <__main__.ProductB object at 0x03968830>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值