博客
关于我
设计模式-结构型-组合模式
阅读量: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/

你可能感兴趣的文章
NFinal学习笔记 02—NFinalBuild
查看>>
NFS共享文件系统搭建
查看>>
nfs复习
查看>>
NFS网络文件系统
查看>>
nft文件传输_利用remoting实现文件传输-.NET教程,远程及网络应用
查看>>
ng 指令的自定义、使用
查看>>
Nginx
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx Location配置总结
查看>>
Nginx upstream性能优化
查看>>
Nginx 中解决跨域问题
查看>>
Nginx 动静分离与负载均衡的实现
查看>>
Nginx 反向代理 MinIO 及 ruoyi-vue-pro 配置 MinIO 详解
查看>>
nginx 反向代理 转发请求时,有时好有时没反应,产生原因及解决
查看>>
Nginx 反向代理解决跨域问题
查看>>
Nginx 反向代理配置去除前缀
查看>>