Menu

  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay
  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay

组合模式

22
Nov
2006

组合模式

By Alex
/ in Architecture
/ tags 设计模式
0 Comments
模式定义

组合模式将对象组合成树,来表现“整体/部分”的层次(树形)结构。组合模式能让客户端以一致的方式处理个别对象以及对象的组合。该模式牺牲了SIP原则来换取操作透明性。组合模式在GOF95中分类为结构型模式。

模式结构与说明

patterns_CompositePattern

  1. 客户端使用Component接口操作组合中的对象
  2. Component定义了组合中所有对象的一致性接口(违反了父类只应当定义对子类有意义的接口这一设计原则)
  3. Composite有持有多个Component的引用,一般用集合表示。这些Component中可能仍然包含Composite
  4. 子节点可以持有父节点的引用,以便简化操作,例如删除自己
  5. 不管是Composite还是Leaf都可以通过operation()进行一致性操作,对客户端来说,这种操作具有透明性
  6. 对SIP原则的违反:Component一方面需要管理树形层次结构,一方面需要执行组件的增删查操作

组合模式的结构可以是递归的,组合模式具有两种组件,统称为节点(Node),其中不带子元素的节点称为叶子节点(Leaf),带子元素的则称为组合(Composite)。

组合模式牵涉到安全性与透明性的权衡问题:

  1. 安全性:从Client的角度来看更安全,不容易发生误操作,能访问的方法都是支持的功能。这需要把接口尽可能的下降到Leaf或者Composite中
  2. 透明性:从Client的角度来看,不需要区分Composite和Leaf。这需要把接口往Component中提升

这两者是冲突的,一般组合模式的实现,倾向于保证透明性,因为这是组合模式本身需要达到的效果。

应用举例

绿湾国际餐厅提供种类繁多的饮食,例如水产类、甜品类、饮料类,其中水产类还分为海鲜类、河鲜类。每种餐品都会标出是否素食、是否冷盘、口味等信息。为了便于客人快速的筛选产品,我们决定基于组合模式与迭代器模式来开发一个快速选菜程序。

Java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
* 菜单和菜单项的公共接口
*/
public abstract class MenuComponent implements Iterable<MenuComponent>
{
 
    /*操作都缺省适配为“不支持”,因为菜单和菜单项的本质差异 */
 
    public void add( MenuComponent component )
    {
        throw new UnsupportedOperationException();
    }
 
    public void remove( MenuComponent component )
    {
        throw new UnsupportedOperationException();
    }
 
    public MenuComponent getChild( int index )
    {
        throw new UnsupportedOperationException();
    }
 
    public String getName()
    {
        throw new UnsupportedOperationException();
    }
 
    public String getDescription()
    {
        throw new UnsupportedOperationException();
    }
 
    public boolean isVegetarian()
    {
        throw new UnsupportedOperationException();
    }
 
    public double getPrice()
    {
        throw new UnsupportedOperationException();
    }
 
}
/**
* 菜单项
*
*/
public class MenuItem extends MenuComponent
{
 
    private String  name;
 
    private String  description;
 
    private boolean vegetarian;
 
    private double  price;
 
    public Iterator<MenuComponent> iterator()
    {
        return new NullIterator();
    }
}
/**
* 菜单
*/
public class Menu extends MenuComponent
{
 
    private String              name;
 
    private String              description;
 
    private List<MenuComponent> menuComponents;
 
    public Iterator<MenuComponent> iterator()
    {
        return new ComponentIterator( menuComponents.iterator() );
    }
}
/**
* 菜单的迭代器,总是返回菜单本身,再依次迭代其子菜单/项
* @author WangZhen
*
*/
public class ComponentIterator implements Iterator<MenuComponent>
{
 
    private Stack<Iterator<MenuComponent>> stack = new Stack<Iterator<MenuComponent>>();
 
    public ComponentIterator( Iterator<MenuComponent> iterator )
    {
        stack.push( iterator ); //底层组合迭代器压在栈底
    }
 
    public boolean hasNext()
    {
        if ( stack.isEmpty() )
        {
            return false;
        }
        else
        {
            Iterator<MenuComponent> it = stack.peek();
            if ( !it.hasNext() )
            {
                stack.pop();
                return hasNext(); //如果暂定迭代器空了,那么弹出并遍历下一个迭代器
            }
            else
            {
                return true;
            }
        }
    }
 
    public MenuComponent next()
    {
        if ( hasNext() )
        {
            Iterator<MenuComponent> it = stack.peek();
            MenuComponent comp = it.next();
            if ( comp instanceof Menu )
            {
                stack.push( comp.iterator() ); //如果当前迭代项是Composite,那么压栈,紧接着遍历它
            }
            return comp;
        }
        else
        {
            return null;
        }
    }
 
    public void remove()
    {
        throw new UnsupportedOperationException();
    }
 
}
/**
* 避免要求客户端代码采用if-else语句进行Null判断,进一步增强操作一致性
*
*/
public class NullIterator implements Iterator<MenuComponent>
{
 
    public boolean hasNext()
    {
        return false;
    }
 
    public MenuComponent next()
    {
        return null;
    }
 
    public void remove()
    {
        throw new UnsupportedOperationException();
 
    }
 
}
 
//测试代码
public static void main( String[] args )
{
    for ( MenuComponent comp : menu )
    {
        //挑选出所有素食
        if ( comp.isVegetarian() )
            System.out.println( comp.getName() );
    }
}
经典应用
UI框架中的组件层次

组合模式在UI框架中被大量的使用,例如Java中AWT的组件类层次结构如下:

patterns_CompositePattern_AWT

其中Component是所有UI控件的超类,而Container则相当于Composite角色,一个Container中可以包含多种控件,包括其它Container。

ExtJS的组件框架的也包含组件模式的应用:

patterns_CompositePattern_Ext_1

ExtJS中的CompositeElement

Ext.dom.CompositeElement实现了组合模式的变体,它虽然不支持树状结构,但是为Composite角色和Leaf角色提供了一致的接口:

JavaScript
1
2
3
4
5
//select方法返回CompositeElement
var els = Ext.select("#some-el div.some-class", true);
els.setWidth(100); //对组合设置宽度,相当于对所有元素设置宽度
els.hide(true); //设置所有元素的隐藏属性
els.setWidth(100).hide(true); //链式调用

在ExtJS中类似的组合模式还有Ext.fx.target.CompositeSprite、Ext.fx.target.CompositeElement等。 

模式演变
  1. 与迭代器模式联用,用来遍历整个Component树
  2. 与访问者模式联用,可以把分散在Composite和Leaf类中的操作抽取出来,转移到访问者中
  3. 与职责链模式联用,可以方便的把职责分配到树节点上
← 迭代器模式
状态模式 →

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Related Posts

  • 享元模式
  • 访问者模式
  • 工厂模式
  • 服务定位器模式
  • 迭代器模式

Recent Posts

  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
  • A Comprehensive Study of Kotlin for Java Developers
  • 背诵营笔记
  • 利用LangChain和语言模型交互
  • 享学营笔记
ABOUT ME

汪震 | Alex Wong

江苏淮安人,现居北京。目前供职于腾讯云,专注容器方向。

GitHub:gmemcc

Git:git.gmem.cc

Email:gmemjunk@gmem.cc@me.com

ABOUT GMEM

绿色记忆是我的个人网站,域名gmem.cc中G是Green的简写,MEM是Memory的简写,CC则是我的小天使彩彩名字的简写。

我在这里记录自己的工作与生活,同时和大家分享一些编程方面的知识。

GMEM HISTORY
v2.00:微风
v1.03:单车旅行
v1.02:夏日版
v1.01:未完成
v0.10:彩虹天堂
v0.01:阳光海岸
MIRROR INFO
Meta
  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
Recent Posts
  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
    In this blog post, I will walk ...
  • A Comprehensive Study of Kotlin for Java Developers
    Introduction Purpose of the Study Understanding the Mo ...
  • 背诵营笔记
    Day 1 Find Your Greatness 原文 Greatness. It’s just ...
  • 利用LangChain和语言模型交互
    LangChain是什么 从名字上可以看出来,LangChain可以用来构建自然语言处理能力的链条。它是一个库 ...
  • 享学营笔记
    Unit 1 At home Lesson 1 In the ...
  • K8S集群跨云迁移
    要将K8S集群从一个云服务商迁移到另外一个,需要解决以下问题: 各种K8S资源的迁移 工作负载所挂载的数 ...
  • Terraform快速参考
    简介 Terraform用于实现基础设施即代码(infrastructure as code)—— 通过代码( ...
  • 草缸2021
    经过四个多月的努力,我的小小荷兰景到达极致了状态。

  • 编写Kubernetes风格的APIServer
    背景 前段时间接到一个需求做一个工具,工具将在K8S中运行。需求很适合用控制器模式实现,很自然的就基于kube ...
  • 记录一次KeyDB缓慢的定位过程
    环境说明 运行环境 这个问题出现在一套搭建在虚拟机上的Kubernetes 1.18集群上。集群有三个节点: ...
  • eBPF学习笔记
    简介 BPF,即Berkeley Packet Filter,是一个古老的网络封包过滤机制。它允许从用户空间注 ...
  • IPVS模式下ClusterIP泄露宿主机端口的问题
    问题 在一个启用了IPVS模式kube-proxy的K8S集群中,运行着一个Docker Registry服务 ...
  • 念爷爷
      今天是爷爷的头七,十二月七日、阴历十月廿三中午,老人家与世长辞。   九月初,回家看望刚动完手术的爸爸,发

  • 6 杨梅坑

  • liuhuashan
    深圳人才公园的网红景点 —— 流花山

  • 1 2020年10月拈花湾

  • 内核缺陷触发的NodePort服务63秒延迟问题
    现象 我们有一个新创建的TKE 1.3.0集群,使用基于Galaxy + Flannel(VXLAN模式)的容 ...
  • Galaxy学习笔记
    简介 Galaxy是TKEStack的一个网络组件,支持为TKE集群提供Overlay/Underlay容器网 ...
TOPLINKS
  • Zitahli's blue 91 people like this
  • 梦中的婚礼 64 people like this
  • 汪静好 61 people like this
  • 那年我一岁 36 people like this
  • 为了爱 28 people like this
  • 小绿彩 26 people like this
  • 彩虹姐姐的笑脸 24 people like this
  • 杨梅坑 6 people like this
  • 亚龙湾之旅 1 people like this
  • 汪昌博 people like this
  • 2013年11月香山 10 people like this
  • 2013年7月秦皇岛 6 people like this
  • 2013年6月蓟县盘山 5 people like this
  • 2013年2月梅花山 2 people like this
  • 2013年淮阴自贡迎春灯会 3 people like this
  • 2012年镇江金山游 1 people like this
  • 2012年徽杭古道 9 people like this
  • 2011年清明节后扬州行 1 people like this
  • 2008年十一云龙公园 5 people like this
  • 2008年之秋忆 7 people like this
  • 老照片 13 people like this
  • 火一样的六月 16 people like this
  • 发黄的相片 3 people like this
  • Cesium学习笔记 90 people like this
  • IntelliJ IDEA知识集锦 59 people like this
  • Bazel学习笔记 38 people like this
  • 基于Kurento搭建WebRTC服务器 38 people like this
  • PhoneGap学习笔记 32 people like this
  • NaCl学习笔记 32 people like this
  • 使用Oracle Java Mission Control监控JVM运行状态 29 people like this
  • Ceph学习笔记 27 people like this
  • 基于Calico的CNI 27 people like this
Tag Cloud
ActiveMQ AspectJ CDT Ceph Chrome CNI Command Cordova Coroutine CXF Cygwin DNS Docker eBPF Eclipse ExtJS F7 FAQ Groovy Hibernate HTTP IntelliJ IO编程 IPVS JacksonJSON JMS JSON JVM K8S kernel LB libvirt Linux知识 Linux编程 LOG Maven MinGW Mock Monitoring Multimedia MVC MySQL netfs Netty Nginx NIO Node.js NoSQL Oracle PDT PHP Redis RPC Scheduler ServiceMesh SNMP Spring SSL svn Tomcat TSDB Ubuntu WebGL WebRTC WebService WebSocket wxWidgets XDebug XML XPath XRM ZooKeeper 亚龙湾 单元测试 学习笔记 实时处理 并发编程 彩姐 性能剖析 性能调优 文本处理 新特性 架构模式 系统编程 网络编程 视频监控 设计模式 远程调试 配置文件 齐塔莉
Recent Comments
  • qg on Istio中的透明代理问题
  • heao on 基于本地gRPC的Go插件系统
  • 黄豆豆 on Ginkgo学习笔记
  • cloud on OpenStack学习笔记
  • 5dragoncon on Cilium学习笔记
  • Archeb on 重温iptables
  • C/C++编程:WebSocketpp(Linux + Clion + boostAsio) – 源码巴士 on 基于C/C++的WebSocket库
  • jerbin on eBPF学习笔记
  • point on Istio中的透明代理问题
  • G on Istio中的透明代理问题
  • 绿色记忆:Go语言单元测试和仿冒 on Ginkgo学习笔记
  • point on Istio中的透明代理问题
  • 【Maven】maven插件开发实战 – IT汇 on Maven插件开发
  • chenlx on eBPF学习笔记
  • Alex on eBPF学习笔记
  • CFC4N on eBPF学习笔记
  • 李运田 on 念爷爷
  • yongman on 记录一次KeyDB缓慢的定位过程
  • Alex on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • haolipeng on 基于本地gRPC的Go插件系统
  • 吴杰 on 基于C/C++的WebSocket库
©2005-2025 Gmem.cc | Powered by WordPress | 京ICP备18007345号-2