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

你可能感兴趣的文章
NVIDIA-cuda-cudnn下载地址
查看>>
nvidia-htop 使用教程
查看>>
nvidia-smi 参数详解
查看>>
nvm安装以后,node -v npm 等命令提示不是内部或外部命令 node多版本控制管理 node多版本随意切换
查看>>
NYOJ 1066 CO-PRIME(数论)
查看>>
nyoj------203三国志
查看>>
nyoj58 最少步数
查看>>
OAuth2 + Gateway统一认证一步步实现(公司项目能直接使用),密码模式&授权码模式
查看>>
OAuth2 Provider 项目常见问题解决方案
查看>>
Vue.js 学习总结(14)—— Vue3 为什么推荐使用 ref 而不是 reactive
查看>>
oauth2-shiro 添加 redis 实现版本
查看>>
OAuth2.0_JWT令牌-生成令牌和校验令牌_Spring Security OAuth2.0认证授权---springcloud工作笔记148
查看>>
OAuth2.0_JWT令牌介绍_Spring Security OAuth2.0认证授权---springcloud工作笔记147
查看>>
OAuth2.0_介绍_Spring Security OAuth2.0认证授权---springcloud工作笔记137
查看>>
OAuth2.0_完善环境配置_把资源微服务客户端信息_授权码存入到数据库_Spring Security OAuth2.0认证授权---springcloud工作笔记149
查看>>
OAuth2.0_授权服务配置_Spring Security OAuth2.0认证授权---springcloud工作笔记140
查看>>
OAuth2.0_授权服务配置_令牌服务和令牌端点配置_Spring Security OAuth2.0认证授权---springcloud工作笔记143
查看>>
OAuth2.0_授权服务配置_客户端详情配置_Spring Security OAuth2.0认证授权---springcloud工作笔记142
查看>>
OAuth2.0_授权服务配置_密码模式及其他模式_Spring Security OAuth2.0认证授权---springcloud工作笔记145
查看>>
OAuth2.0_授权服务配置_资源服务测试_Spring Security OAuth2.0认证授权---springcloud工作笔记146
查看>>