组合模式

来源:互联网 发布:风乎舞雩的乎 编辑:程序博客网 时间:2024/06/06 02:53

简单来说,就是一个复杂的对象里可以包含其他对象,
如下面
一个盒子里面可以放进其他东西

from abc import abstractmethodclass item:    @abstractmethod    def __init__(self,name,price):        pass    @abstractmethod    def printprice(self):        passclass pen(item):    def __init__(self,name,price):        self.name = name        self.price = price    def printprice(self):        print "pen:{}$".format(self.price)class rule(item):    def __init__(self,name,price):        self.name = name        self.price = price    def printprice(self):        print "rule:{}$".format(self.price)class box(item):    def __init__(self,name,price):        self.name = name        self.price = price        self.children = []    def printprice(self):        print "box:{}$".format(self.price)        for i in self.children:            i.printprice()    def add(self,items):        if items:            self.children.append(items)pen01 = pen('pen',1)rule01 = rule('rule',1)box01 = box('box',2)box01.add(pen01)box01.add(rule01)box01.printprice()
0 0
原创粉丝点击