python实现Composite模式

#-*-coding:utf-8-*-

'''
意图:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
'''
from abc import ABCMeta

class Component():
    __metaclass__ = ABCMeta
    def __init__(self):
        pass
    def operation(self):
        pass
    def add(self, com):
        if not isinstance(comp, Component):
            raise 'add method first argument shuld be a instance of Component!'
        
    def remove(self, comp):
        if not isinstance(comp, Component):
            raise 'remove method first argument shuld be a instance of Component!'
        
    def getChild(self, index):
        if not isinstance(index, int):
            raise 'getChild method first argument should be int type!'
    
class Composite(Component):
    compList = []
    def operation(self):
        for comp in tuple(self.compList):
            comp.operation()
            
    def add(self, comp):
        if not isinstance(comp, Component):
            raise 'add method first argument shuld be a instance of Component!'
        self.compList.append(comp)
        
    def remove(self, comp):
        if not isinstance(comp, Component):
            raise 'remove method first argument shuld be a instance of Component!'
        index = None
#        try:
#            index = self.compList.index(comp)
#        except:
#            raise "comp does't exists"
        #不用上面的,用index中的except机制,减少try使用耗时间
        index = self.compList.index(comp)
        if index is not None:
            del self.compList[index]
    def getChild(self, index):
        if not isinstance(index, int):
            raise 'getChild method first argument should be int type!'
        return self.compList[index]

class Leaf(Component):
    def operation(self):
        print 'Leaf operation...'


if __name__ == "__main__":
     leaf = Leaf()
     leaf.operation()
     
     composite = Composite()
     composite.add(leaf)
     composite.operation()
     
     leaf1 = composite.getChild(0)
     leaf1.operation()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值