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

你可能感兴趣的文章
Netty工作笔记0011---Channel应用案例2
查看>>
Netty工作笔记0014---Buffer类型化和只读
查看>>
Netty工作笔记0050---Netty核心模块1
查看>>
Netty工作笔记0084---通过自定义协议解决粘包拆包问题2
查看>>
Netty常见组件二
查看>>
netty底层源码探究:启动流程;EventLoop中的selector、线程、任务队列;监听处理accept、read事件流程;
查看>>
Netty核心模块组件
查看>>
Netty框架的服务端开发中创建EventLoopGroup对象时线程数量源码解析
查看>>
Netty源码—2.Reactor线程模型一
查看>>
Netty源码—4.客户端接入流程一
查看>>
Netty源码—4.客户端接入流程二
查看>>
Netty源码—5.Pipeline和Handler一
查看>>
Netty源码—6.ByteBuf原理二
查看>>
Netty源码—7.ByteBuf原理三
查看>>
Netty源码—7.ByteBuf原理四
查看>>
Netty源码—8.编解码原理二
查看>>
Netty源码解读
查看>>
Netty的Socket编程详解-搭建服务端与客户端并进行数据传输
查看>>
Netty相关
查看>>
Network Dissection:Quantifying Interpretability of Deep Visual Representations(深层视觉表征的量化解释)
查看>>