九、 合成(Composite)模式 --结构模式(Structural Pattern)
2016-02-24 16:26
375 查看
合成模式:有时又叫做部分-整体模式(Part-Whole)。合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式可以使客户端将单纯元素与复合元素同等看待。
合成模式分为安全式和透明式
安全式合成模式类图:
View Code
运行结果:
使用时注意问题:
1、明显的给出父对象的引用。在子对象里面给出父对象的引用,可以很容易的遍历所有父对象。有了这个引用,可以方便的应用责任链模式。
2、在通常的系统里,可以使用享元模式实现构件的共享,但是由于合成模式的对象经常要有对父对象的引用,因此共享不容易实现。
3、有时候系统需要遍历一个树枝结构的子构件很多次,这 时候 可以考虑把遍历子构件的结果暂时存储在父构件里面作为缓存。
4、关于使用什么数据类型来存储子对象的问题,在示意性的 代码中使用了 ArrayList,在实际系统中可以使用其它聚 集或数组等。
5、客户端尽量不要直接调用树叶类中的方法,而是借助其父 类(Component)的多态性完成调用,这样可以增加代 码的复用性
合成模式分为安全式和透明式
安全式合成模式类图:
class CompositePartten2 { public static void Main(string[] args) { Composite root = new Composite("rood"); root.Add(new Leaf("Leaf A")); root.Add(new Leaf("Leaf b")); Composite comp = new Composite("Composite X"); comp.Add(new Leaf("Leaf XA")); comp.Add(new Leaf("Leaf XB")); root.Add(comp); root.Add(new Leaf("Leaf C")); // Add and remove a leaf Leaf l = new Leaf("Leaf D"); root.Add(l); root.Remove(l); // Recursively display nodes root.Display(1); Console.ReadKey(); } } abstract class Component { protected string name; public Component(string name) { this.name = name; } public abstract void Add(Component c); public abstract void Remove(Component c); public abstract void Display(int c); } class Composite : Component { private ArrayList children = new ArrayList(); public Composite(string name) : base(name) { } public override void Add(Component c) { children.Add(c); } public override void Remove(Component c) { children.Remove(c); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); foreach (Component item in children) { item.Display(depth + 2); } } } class Leaf : Component { public Leaf(string name) : base(name) { } public override void Add(Component c) { Console.WriteLine("Connot add to leaf"); } public override void Remove(Component c) { Console.WriteLine("Connot remove from a leaf"); } public override void Display(int c) { Console.WriteLine(new String('-', c) + name); } }
View Code
运行结果:
使用时注意问题:
1、明显的给出父对象的引用。在子对象里面给出父对象的引用,可以很容易的遍历所有父对象。有了这个引用,可以方便的应用责任链模式。
2、在通常的系统里,可以使用享元模式实现构件的共享,但是由于合成模式的对象经常要有对父对象的引用,因此共享不容易实现。
3、有时候系统需要遍历一个树枝结构的子构件很多次,这 时候 可以考虑把遍历子构件的结果暂时存储在父构件里面作为缓存。
4、关于使用什么数据类型来存储子对象的问题,在示意性的 代码中使用了 ArrayList,在实际系统中可以使用其它聚 集或数组等。
5、客户端尽量不要直接调用树叶类中的方法,而是借助其父 类(Component)的多态性完成调用,这样可以增加代 码的复用性
相关文章推荐
- Zookeeper、HBase的伪分布
- 本机通过telnet访问虚拟机中的Linux系统(CentOS 6.5)
- 给UIColloectionViewCell设置点击效果,解决点击效果错位的问题
- 开了一个月yunfile的会员,发现没东西可下,做了个软件分享下
- iptables配置
- gcc -I -L -l区别
- 完整java开发中JDBC连接数据库步骤
- 主流的几种推送以及比较
- 调试理解过程
- [ActionScript 3.0] AS3.0根据当天日期获取明天,后天...日期
- js 全选全不选
- 只是记录
- Linux命令整理
- ThreadPoolExecutor的跟踪
- 野鸟装备内测包安装指南
- NavigationView和Toolbar侧滑栏
- 【java基础】Java集合框架之小结
- Git分支
- POJ2318-toys(计算几何基础+二分)
- Java基础提高篇