随笔 - 139  文章 - 0 评论 - 0 阅读 - 33724
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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

角色:

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

 

复制代码
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   longfei2021  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2018-10-19 day07-while,for循环
2018-10-19 day06-三元表达式
2018-10-19 day05-if-else语句
点击右上角即可分享
微信分享提示