前面我们介绍了简单工厂模式,每次添加新的产品需要对工厂代码进行相应修改,后面我们对它进行了一系列的优化,到最后把只需要对新建工厂时的参数进行调整就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>