前言

组合模式属于结构型模式,组合模式主要是针对于树形结构数据。

例如:PPT的图形功能:单个图形可以无限递归成组,组成复杂图形,但是单个图形和复杂图形的操作方法一致;

一、组合模式

1.概念

将对象组合成树形结构以表示 部分---整体的层次结构。

组合模式使得用户对单个对象和组合对象的使用具有一致性。

2.角色

抽象组件(Component)

叶子组件(Leaf)

复合组件(Composite)

客户端(Client)

3.代码

from abc import ABC, abstractmethod


# 抽象组件--接口
# 无论是简单图形还是组合图形都需要实现Graphic以达到:单个对象和组合对象的使用具有一致性。
class Graphic(ABC):
    @abstractmethod
    def draw(self):
        pass


# 叶子组件1
# 简单图形-点
class Point(Graphic):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"点({self.x},{self.y})"

    def draw(self):
        print(self)


# 叶子组件2
# 简单图形-线
class Line(Graphic):
    # 2点组成1条线
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __str__(self):
        return f"线段[{self.start},{self.end}]"

    def draw(self):
        print(self)


# 复合组件:由多个叶子组件组成
class Picture(Graphic):
    def __init__(self, child_list):
        self.children = []
        for child in child_list:
            self.children.append(child)

    def add(self, child):
        self.children.append(child)

    def draw(self):
        print("-------复合图形-------")
        for child in self.children:
            child.draw()
        print("-------复合图形-------")


# 客户端
if __name__ == '__main__':
    p1 = Point(1, 2)
    p2 = Point(2, 3)
    l1 = Line(start=p1, end=p2)
    pic1 = Picture([p1, p2, l1])

    p3 = Point(5, 6)
    p4 = Point(8, 7)
    l3 = Line(start=p3, end=p4)
    pic2 = Picture([p3, p4, l3])

    pic3 = Picture([pic1, pic2])
    pic3.draw()

 

 

 

 

参考

posted on 2024-02-17 19:45  Martin8866  阅读(2)  评论(0编辑  收藏  举报