组合模式(Composite):将对象组合成树形结构以表示“部分——整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
透明方式:也就是说在Component中声明所有用来管理子对象的方法,其中包括Add、Remove等。这样实现Component接口的所有子类都具备了Add和Remove。这样做的好处就是叶节点和枝节点对于外界没有区别,它们具备完全一致的接口。但是问题也很明显,因为Leaf类本身不具备Add()、Remove()方法的功能,所以实现它是没有意义的。
安全方式:也就是在Component接口中不去声明Add和Remove方法,那么子类的Leaf也就不需要去实现它,而是在Composite声明所有用来管理子类对象的方法,不过由于不够透明,所以树叶和树枝类将不具有相同的接口,客户端的调用需要做相应的判断,带来了不便。
- using System;
- using System.Collections.Generic;
- /**
- *组合模式(Composite):将对象组合成树形结构以表示“部分——整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
- 透明方式:也就是说在Component中声明所有用来管理子对象的方法,其中包括Add、Remove等。这样实现Component接口的所有子类都具备了Add和Remove。这样做的好处就是叶节点和枝节点对于外界没有区别,它们具备完全一致的接口。但是问题也很明显,因为Leaf类本身不具备Add()、Remove()方法的功能,所以实现它是没有意义的。
- 安全方式:也就是在Component接口中不去声明Add和Remove方法,那么子类的Leaf也就不需要去实现它,而是在Composite声明所有用来管理子类对象的方法,不过由于不够透明,所以树叶和树枝类将不具有相同的接口,客户端的调用需要做相应的判断,带来了不便。
- */
- namespace StuDesignMode.Composite
- {
- #region 组合模式
- abstract class AbsComponent
- {
- protected string Name { get; set; }
- public AbsComponent(string name)
- {
- this.Name = name;
- }
- public abstract void Add(AbsComponent c);
- public abstract void Remove(AbsComponent c);
- public abstract void Display(int depth);
- }
- class Leaf : AbsComponent
- {
- public Leaf(string name) : base(name) { }
- public override void Add(AbsComponent c)
- {
- Console.WriteLine("Cannot add to a leaf!");
- }
- public override void Remove(AbsComponent c)
- {
- Console.WriteLine("Cannot remove to a leaf!");
- }
- public override void Display(int depth)
- {
- Console.WriteLine(new String('—',depth)+this.Name);
- }
- }
- class Composite : AbsComponent
- {
- private List<AbsComponent> childdren = new List<AbsComponent>();
- private Composite(string name):base(name){}
- public override void Add(AbsComponent c)
- {
- childdren.Add(c);
- }
- public override void Remove(AbsComponent c)
- {
- childdren.Remove(c);
- }
- public override void Display(int depth)
- {
- Console.WriteLine(new String('—',depth)+this.Name);
- foreach (var item in childdren)
- {
- item.Display(depth + 2);
- }
- }
- class ClientTest
- {
- static void Main(string[] args)
- {
- Composite root = new Composite("root");
- root.Add(new Leaf("A"));
- root.Add(new Leaf("B"));
- Composite comp = new Composite("comp");
- comp.Add(new Leaf("x"));
- comp.Add(new Leaf("y"));
- root.Add(comp);
- root.Display(1);
- }
- }
- }
- #endregion
- }