public abstract class Component { protected string _name; public Component(string name) { _name = name; } public abstract void Operation(); public abstract void Add(Component component); public abstract void Remove(Component component); }
public class Leaf : Component { public Leaf(string name) : base(name) { } public override void Add(Component component) { throw new NotSupportedException(); } public override void Remove(Component component) { throw new NotSupportedException(); }
public override void Operation() { //...do something } }
public class Composite : Component { public Composite(string name):base(name){} List<Component> list = new List<Component>(); /// <summary> /// 添加 /// </summary> /// <param name="conponent"></param> public override void Add(Component component) { if (list != null) { list = new List<Component>(); } list.Add(component); } /// <summary> /// 删除 /// </summary> /// <param name="component"></param> public override void Remove(Component component) { if (list == null) { throw new NullReferenceException(); } list.Remove(component); }
public override void Operation() { if (list != null) { foreach (Component c in list) { c.Operation(); } } } }