设计模式-9-组合
说明
所有组件继承抽象组件,并可在任何组件中组合该抽象组件,使之具有全部组件遍历的能力,并可任意的增加组件,且每个组件可以完全不同.
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);