Composite Pattern Demo
using System; using System.Text; using System.Collections; public abstract class Unit { protected string name; public abstract void Add(Unit e); public abstract void Remove(Unit e); public abstract void GetChild(int level); public Unit(string name) { this.name = name; } } public class Office : Unit { public override void Add(Unit c) { Console.WriteLine("Can't use 'Add' in Office!"); } public override void Remove(Unit e) { Console.WriteLine("Can't use 'Remove' in Office! "); } public override void GetChild(int level) { Console.WriteLine(new string('*', level) + this.name); } public Office(string name) : base(name) {} } public class Branch : Unit { private ArrayList node = new ArrayList(); public override void Add(Unit e) { node.Add(e); } public override void Remove(Unit e) { node.Remove(e); } public override void GetChild(int level) { Console.WriteLine(new String('#', level) + this.name); foreach (Unit e in this.node) e.GetChild(level + 1); } public Branch(string name) : base(name) {} } public class Client { static void Main(string[] args) { Branch root = new Branch("US (Root)"); Office ny = new Office("A (Unit)"); Office ca = new Office("B (Unit)"); root.Add(ny); root.Add(ca); Branch rootHawaii = new Branch("Canada Branch (Branch)"); root.Add(rootHawaii); Branch branchUK = new Branch("UK Branch (Branch)"); Office ldnc = new Office("C Office (Unit)"); Office ldnw = new Office("D Office (Unit)"); branchUK.Add(ldnc); branchUK.Add(ldnw); root.Add(branchUK); Office dummy = new Office("D Office"); ldnc.Add(dummy); root.GetChild(0); root.Remove(rootHawaii); branchUK.Remove(ldnc); Console.WriteLine("Remove Hawaii branch and London City office"); root.GetChild(0); } }