美文网首页生活不易 我用python
【Python 设计模式】 01 Factory Method

【Python 设计模式】 01 Factory Method

作者: Young_W_F | 来源:发表于2018-08-02 10:13 被阅读7次

Factory Method 工厂方法模式

  1. 说明

工厂模式包涵一个超类,这个超类提供一个抽象化的接口来实例化一个特定类型的对象。

  1. UML
Factory_Method.png
  1. 代码
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)

相关文章

网友评论

    本文标题:【Python 设计模式】 01 Factory Method

    本文链接:https://www.haomeiwen.com/subject/iukjvftx.html