设计模式-组合模式
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、很难对各层次中的对象加特别处理。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。