說明node
全部組件繼承抽象組件,並可在任何組件中組合該抽象組件,使之具備所有組件遍歷的能力,並可任意的增長組件,且每一個組件能夠徹底不一樣.ide
public abstract class AbsComponent { public string name { get; set; } public AbsComponent(string _name) { name = _name; } public abstract void Exc(int depth); } public class ComponentA : AbsComponent { public ComponentA(string _name) : base(_name) { lComponent = new List<AbsComponent>(); } public List<AbsComponent> lComponent { get; set; } public override void Exc(int depth) { Console.WriteLine(new String('-', depth) + name); foreach (var component in lComponent) component.Exc(depth + 2); } } public class ComponentB : AbsComponent { public ComponentB(string _name) : base(_name) { } public override void Exc(int depth) { Console.WriteLine(new String('-', depth) + name); } } var root = new ComponentA("root"); root.lComponent.Add(new ComponentB("Leaf A")); root.lComponent.Add(new ComponentB("Leaf B")); ComponentA comp = new ComponentA("Composite X"); comp.lComponent.Add(new ComponentB("Leaf XA")); comp.lComponent.Add(new ComponentB("Leaf XB")); root.lComponent.Add(comp); root.lComponent.Add(new ComponentB("Leaf C")); // Add and remove a leaf var l = new ComponentB("Leaf D"); root.lComponent.Add(l); root.lComponent.Remove(l); // Recursively display nodes root.Exc(1);