组合模式,Composite
来源:互联网 发布:概率矩阵分解 视频 编辑:程序博客网 时间:2024/06/15 16:44
组合模式的定义是:
把对象组成成树型结构,来表示“部分-整体”的分层。让客户一致地对待单独的对象和组合的对象。
其UML类图的示例如下:
在这个模式中,参与者包括:
- Component:
- 声明组合中用于对象的接口。
- 为所有类共有的接口实现默认行为。
- 声明一个接口用于访问和管理其子组件。
- (可选)定义一个接口用于访问组件的递归结构中的父组件,如果可能的话,实现此接口。
- Leaf:
- 表示组合中的叶子对象,叶子节点没有子节点。
- 定义组合中的基础对象的行为。
- Composite:
- 定义有子节点的组件的行为。
- 存储子组件。
- 实现组件接口中子节点相关的操作。
- Client:通过Component接口操作组合中的对象。
实现代码:
public interface Component{ void Operation();} public class Composite : Component, IEnumerable{ private List _children = new List(); public void AddChild(Component child) { _children.Add(child); } public void RemoveChild(Component child) { _children.Remove(child); } public Component GetChild(int index) { return _children[index]; } public void Operation() { string message = string.Format("Composite with {0} child(ren)", _children.Count); Console.WriteLine(message); } public IEnumerator GetEnumerator() { foreach (Component child in _children) yield return child; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }}public class Leaf : Component{ public void Operation() { Console.WriteLine("Leaf"); }}
- 需要分层的表示对象。
- 单个对象和一组对象应该以相同的方式对待。
- 组合模式用于当数据被组织成树结构(比如目录)的时候。
0 0
- Composite模式 组合模式
- 组合模式:Composite模式
- 组合模式(Composite)
- Composite组合模式
- 组合模式-Composite Pattern
- Composite 组合模式
- Composite Pattern(组合模式)
- 组合模式(Composite)
- Composite组合模式
- 组合模式(Composite)
- 组合模式Composite
- Composite 组合模式
- Composite(组合模式)
- java Composite 组合模式
- Composite 组合模式
- 组合模式(Composite Patten)
- Composite(组合模式)
- 11.组合模式--Composite
- Shiro的 rememberMe 功能使用指导(为什么rememberMe设置了没作用?)
- CSS专题(二):元素大小与位置offsetLeft offsetTop offsetWidth offsetHeight clientWidth clientHeight scrollWidth s
- JAVA默认排序算法问题
- Jsp静态包含和动态包含
- C++结构的大小
- 组合模式,Composite
- js中通过 CSS 选择器选取元素
- c3p0配置详解
- 对canvas的translate()方法的理解
- hdu 4526 水DP
- sublime 经验总结 主题有 less2css
- hta文件格式
- 使用oracle官方文档(11G)——初探Concept
- 【C语言学习】存储类型