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

    image.png

    1. from abc import abstractmethod, ABCMeta
    2. class Graphic(metaclass=ABCMeta):
    3. @abstractmethod
    4. def draw(self):
    5. raise NotImplemented
    6. @abstractmethod
    7. def add(self):
    8. raise NotImplemented
    9. def getchildren(self):
    10. pass
    11. class Point(Graphic):
    12. def __init__(self, x, y):
    13. self.x = x
    14. self.y = y
    15. def draw(self):
    16. print(self)
    17. def add(self, graphic):
    18. raise TypeError
    19. def getchildren(self):
    20. raise TypeError
    21. def __str__(self):
    22. return "点(%s, %s)" % (self.x, self.y)
    23. class Line(Graphic):
    24. def __init__(self, p1, p2):
    25. self.p1 = p1
    26. self.p2 = p2
    27. def draw(self):
    28. print(self)
    29. def add(self, graphic):
    30. raise TypeError
    31. def getchchildren(self):
    32. raise TypeError
    33. def __str__(self):
    34. return "线段[%s, %s]" % (self.p1, self.p2)
    35. class Picture(Graphic):
    36. def __init__(self):
    37. self.children = []
    38. def add(self, graphic):
    39. self.children.append(graphic)
    40. def getchildren(self):
    41. return self.children
    42. def draw(self):
    43. print("-------复合图形-------")
    44. for g in self.children:
    45. g.draw()
    46. print("------END--------")
    47. pic1 = Picture()
    48. point = Point(2, 3)
    49. pic1.add(point)
    50. pic1.add(Line(Point(1, 2), Point(4, 5)))
    51. pic1.add(Line(Point(0, 1), Point(2, 1)))
    52. pic2 = Picture()
    53. pic2.add(Point(-2, -1))
    54. pic2.add(Line(Point(0, 0), Point(1, 1)))
    55. pic = Picture()
    56. pic.add(pic1)
    57. pic.add(pic2)
    58. pic.draw()
    59. pic1.draw()
    60. point.draw()