- 内容:将对象组合成树形结构以表示 “部分-整体” 的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
- 角色:
- 抽象组件(Component)
- 叶子组件(Leaf)
- 复合组件(Composite)
- 客户端(Client)

from abc import abstractmethod, ABCMetaclass Graphic(metaclass=ABCMeta): @abstractmethod def draw(self): raise NotImplemented @abstractmethod def add(self): raise NotImplemented def getchildren(self): passclass Point(Graphic): def __init__(self, x, y): self.x = x self.y = y def draw(self): print(self) def add(self, graphic): raise TypeError def getchildren(self): raise TypeError def __str__(self): return "点(%s, %s)" % (self.x, self.y)class Line(Graphic): def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 def draw(self): print(self) def add(self, graphic): raise TypeError def getchchildren(self): raise TypeError def __str__(self): return "线段[%s, %s]" % (self.p1, self.p2)class Picture(Graphic): def __init__(self): self.children = [] def add(self, graphic): self.children.append(graphic) def getchildren(self): return self.children def draw(self): print("-------复合图形-------") for g in self.children: g.draw() print("------END--------")pic1 = Picture()point = Point(2, 3)pic1.add(point)pic1.add(Line(Point(1, 2), Point(4, 5)))pic1.add(Line(Point(0, 1), Point(2, 1)))pic2 = Picture()pic2.add(Point(-2, -1))pic2.add(Line(Point(0, 0), Point(1, 1)))pic = Picture()pic.add(pic1)pic.add(pic2)pic.draw()pic1.draw()point.draw()