Factory Method 工厂方法模式
- 说明
工厂模式包涵一个超类,这个超类提供一个抽象化的接口来实例化一个特定类型的对象。
- UML
- 代码
from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def use(self):
'''使用产品'''
class Factory(ABC):
def create(self, owner):
p = self._create_product(owner)
self._register_product(p)
return p
@abstractmethod
def _create_product(self, owner) -> Product:
'''创建产品'''
@abstractmethod
def _register_product(self, Product):
'''注册产品'''
class IDCard(Product):
def __init__(self, owner):
print('制作' + owner + '的ID卡')
self.owner = owner
def use(self):
print('使用{}的ID卡'.format(self.owner) )
def get_owner(self):
return self.owner
class IDCardFactory(Factory):
def __init__(self):
self.owners = []
def _create_product(self, owner):
return IDCard(owner)
def _register_product(self, Product):
self.owners.append(Product.owner)
def get_owners(self):
return self.owners
if __name__ == '__main__':
id_factory_1 = IDCardFactory()
id_factory_2 = IDCardFactory()
foo = id_factory_1.create('小红')
bar = id_factory_1.create('小蓝')
baz = id_factory_2.create('小李')
foo.use()
bar.use()
print(id_factory_1.owners)
print(id_factory_2.owners)
网友评论