python 设计模式-组合模式

组合模式强调整体和部分的层次关系,以及整体和部分对外接口的一致性。示例代码如下:

from abc import ABCMeta, abstractmethod
from collections import OrderedDict


class Component(metaclass=ABCMeta):
    def __init__(self, attr):
        self._attr = attr

    @abstractmethod
    def oper(self):
        pass
    

class Leaf(Component):
    def oper(self):
        print('attr: {}, leaf oper'.format(self._attr))


class Composite(Component):
    def __init__(self, attr):
        super(Composite, self).__init__(attr)
        self._subs = set()

    def oper(self):
        print('attr: {}, composite oper'.format(self._attr))
        for c in self._subs:
            c.oper() 

    def add(self, comp):
        self._subs.add(comp)
    
    def remove(self, comp):
        self._subs.remove(comp)


if __name__ == '__main__':
    c = Composite('c')
    c1 = Composite('c1')
    c2 = Composite('c2')
    l1 = Leaf('l1')
    l2 = Leaf('l2')
    c.add(c1)
    c1.add(c2)
    c2.add(l1)
    c2.add(l2)
    c.oper()

输出:

attr: c, composite oper
attr: c1, composite oper
attr: c2, composite oper
attr: l2, leaf oper
attr: l1, leaf oper

你可能感兴趣的:(python)