本文共 1267 字,大约阅读时间需要 4 分钟。
import abcfrom abc import ABCMeta, abstractmethod 抽象组件类 class Graphic(metaclass=ABCMeta):@abstractmethoddef draw(self):pass 叶子组件 class Point(Graphic):def init(self, x, y):self.x = xself.y = ydef str(self):return f"Point({self.x}, {self.y})"def draw(self):print(str(self)) 边 class Line(Graphic):def init(self, p1, p2):self.p1 = p1self.p2 = p2def str(self):return f"Line[{self.p1}, {self.p2}]"def draw(self):print(str(self)) 复合组件 class Picture(Graphic):def init(self, iterable):self.children = []for i in iterable:self.add(i)def add(self, graphic):self.children.append(graphic)def draw(self):print("---复合图形---")for child in self.children:child.draw()print("---复合图形---") 示例使用 p1 = Point(2, 3)l1 = Line(Point(3, 4), Point(6, 7))l2 = Line(Point(3, 5), Point(6, 8))pic1 = Picture([p1, l1, l2])pic1.draw() p2 = Point(3, 3)l3 = Line(Point(4, 4), Point(7, 7))l4 = Line(Point(5, 5), Point(8, 8))pic2 = Picture([p2, l3, l4])pic2.draw() pic = Picture([pic1, pic2])pic.draw() 转载地址:http://duec.baihongyu.com/