码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-组合模式

时间:2018-05-20 18:03:51      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:设计模式   组合模式   

abstract class Component { protected string name; public Component(string _name) { name = _name; } public abstract void Add(Component c); public abstract void Remove(Component c); public abstract void Display(int depth); } class Leaf : Component { public Leaf(string _name) : base(_name) { } public override void Add(Component c) { Console.WriteLine("叶子不允许添加"); } public override void Remove(Component c) { Console.WriteLine("叶子不允许移除子节点"); } public override void Display(int depth) { Console.WriteLine(new string(‘-‘,depth)+name); } } class Composite : Component { List<Component> childList = new List<Component>(); public Composite(string _name) : base(_name) { } public override void Add(Component c) { childList.Add(c); } public override void Remove(Component c) { childList.Remove(c); } public override void Display(int depth) { Console.WriteLine(new string(‘-‘, depth) + name); foreach (var item in childList) { item.Display(depth + 2); } } } //前端 static void Main(string[] args) { Component c = new Composite("总公司"); Component c1 = new Leaf("财务部"); Component c2 = new Leaf("人事部"); Component c3 = new Composite("南京分公司"); c.Add(c1); c.Add(c2); c.Add(c3); c3.Add(c1); c3.Add(c2); c1.Add(c2); c3.Display(1); Console.ReadLine(); }

总结:当需求是体现了部分与整体的层次结构时,但是可以忽略单个对象与组合对象的不同,而统一使用结构中的所有对象的时候,可以 用组合模式。
优点:
1、对象可以无限组合,可以使用单个对象的地方就可以使用组合对象。
2、可以一致的使用单个对象或是组合对象。
3、可以很轻松的扩展
缺点:
1、不直观;
2、设计太抽象,应对复杂业务时,使用组合模式得三思。
3、很难对各层次中的对象加特别处理。

技术分享图片

设计模式-组合模式

标签:设计模式   组合模式   

原文地址:http://blog.51cto.com/5591787/2118449

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!