博客
关于我
设计模式-结构型-组合模式
阅读量:186 次
发布时间:2019-02-28

本文共 1267 字,大约阅读时间需要 4 分钟。

文章目录

组合模式

概述

  • 组合模式通过将对象组合成树形结构,体现“部分与整体”的层次关系,使得用户可以一致地处理单个对象和组合对象

对象

  • 抽象组件 (Component):定义了所有组件的共同接口,确保组件之间的兼容性
  • 叶子组件 (Leaf):无法再分解的最基本组件,通常是叶节点
  • 复合组件 (Composite):由多个组件组成的组合对象,代表了“部分与整体”的关系
  • 客户端 (Client):使用组合模式的最终用户或应用程序

适用场景

  • 需要表示复杂对象的层次结构
  • 希望无缝处理单个对象和组合对象

示例

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/

你可能感兴趣的文章
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>