将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使用户对单个对象和组合对象的使用具有一致性。

角色:

  • 抽象组件
  • 叶子组件
  • 复合组件
  • 客户端

 

from abc import ABCMeta,abstractmethod

class Graphic:
    @abstractmethod
    def draw(self):
        pass

class Point(Graphic):
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __str__(self):
        return 'point %s:%s'%(self.x,self.y)

    def draw(self):
        print(str(self))

class Line(Graphic):
    def __init__(self,p1,p2):
        self.p1 = p1
        self.p2 = p2

    def __str__(self):
        return "line %s-%s"%(self.p1,self.p2)

    def draw(self):
        print(str(self))

class Picture(Graphic):
    def __init__(self,iterable):
        self.children = []
        self.add(iterable)

    def add(self,iterable):
        for i in iterable:
            self.children.append(i)

    def draw(self):
        for g in self.children:
            g.draw()

p1 = Point(1,2)
p2 = Point(2,3)
l1 = Line(p1,p2)

pic1 = Picture([p1,p2,l1])
pic1.draw()

point 1:2
point 2:3
line point 1:2-point 2:3

posted on 2023-10-19 17:44  longfei2021  阅读(3)  评论(0编辑  收藏  举报