享元模式(python)

"""
享元模式
使用共享技术支持大量细粒度的对象
使用几种对象就可以表示所有的对象
应用场景:对象的结构基本相同,但需要生成大量的对象
"""
from abc import ABCMeta, abstractmethod


class Go(object):
    """
    围棋棋子抽象基类
    """
    __metaclass__ = ABCMeta

    def __init__(self, color):
        self.color = color
        pass

    @abstractmethod
    def play(self, position):
        pass


class ConcreteGo(Go):
    def __init__(self, color):
        super(ConcreteGo, self).__init__(color)

    def play(self, position):
        print(self.color + "下在" + str(position) + "上")


class Factory(object):
    def __init__(self):
        self._go_dict = dict()
        pass

    def create_go(self, color):
        if color in self._go_dict:
            return self._go_dict[color]
        else:
            self._go_dict[color] = ConcreteGo(color)
            return self._go_dict[color]

    def count(self):
        print("一共有{0}种棋子,分别是:".format(len(self._go_dict)))
        for k, v in enumerate(self._go_dict):
            print(v)


if __name__ == '__main__':
    factory = Factory()
    white1 = factory.create_go("白棋")
    white1.play(1)
    black1 = factory.create_go("黑棋")
    black1.play(2)
    white2 = factory.create_go("白棋")
    white3 = factory.create_go("白棋")
    white4 = factory.create_go("白棋")
    white2.play(3)
    white3.play(4)
    white4.play(5)

    print("")
    factory.count()





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值