设计模式:组合模式(Composite)
定 义:将对象组合树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象使用具有一致性。
结构图:
Component类:
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 depth); }
Leaf类:
class Leaf : Component { public Leaf(string name) : base(name) { } public override void Add(Component c) { Console.WriteLine("Cannot add a leaf"); } public override void Remove(Component c) { Console.WriteLine("Cannot remove from leaf"); } public override void Display(int depth) { Console.WriteLine(new string('-', depth) + name); } }