个人理解抽象工厂模式就是将工厂方法模式进行了一般化,一个工厂不仅仅只生产一种产品,而是一个产品族。
示例代码如下:
from abc import ABCMeta, abstractmethod
from Tools.scripts.serve import app
class Factory(metaclass=ABCMeta):
@abstractmethod
def produce_laptop(self):
pass
@abstractmethod
def produce_pad(self):
pass
@abstractmethod
def produce_phone(self):
pass
class Laptop(metaclass=ABCMeta):
pass
class Pad(metaclass=ABCMeta):
pass
class Phone(metaclass=ABCMeta):
pass
class Mac(Laptop):
pass
class Ipad(Pad):
pass
class Iphone(Phone):
pass
class Matebook(Laptop):
pass
class Hwpad(Pad):
pass
class Honor(Phone):
pass
class AppleFactory(Factory):
def produce_laptop(self):
return Mac()
def produce_pad(self):
return Ipad()
def produce_phone(self):
return Iphone()
class HuaweiFactory(Factory):
def produce_laptop(self):
return Matebook()
def produce_pad(self):
return Hwpad()
def produce_phone(self):
return Honor()
if __name__ == '__main__':
apple = AppleFactory()
hw = HuaweiFactory()
print('apple: {},{},{}; huawei: {},{},{}'.format(
apple.produce_laptop(),
apple.produce_pad(),
apple.produce_phone(),
hw.produce_laptop(),
hw.produce_pad(),
hw.produce_phone()))
输出:
apple: <__main__.Mac object at 0x03CE4D50>,<__main__.Ipad object at 0x03CE4DB0>,<__main__.Iphone object at 0x03CE4D90>; huawei: <__main__.Matebook object at 0x03CE4CD0>,<__main__.Hwpad object at 0x03CE4E30>,<__main__.Honor object at 0x03CE4E10>