组合模式的透明方式:Component中声明所有用来管理子对象的方法,包括Add Remove等,这样实现Component的所有子类都具备了Add Remove,这样做的好处是叶节点和枝节点对于外界没有区别,它们具备完全一致的行为接口,问题是leaf类本身不具备add remove 方法的功能所以实现它是没有意义的。
安全方式:Component接口中不去声明add和remove方法,子类的leaf不用实现它,而是在Composite声明所有用来管理子类对象的方法,不过由于不够透明,所以树叶和树枝类将不具有相同的接口,客户端的调用需要做相应的判断,不方便。
抽象类:
public abstract class AbstractClass { public string name; public ArrayList list; public abstract void Add(AbstractClass item); //增加一个子节点 public abstract void Remove(AbstractClass item); //去掉一个子节点 public abstract string Print(); //打印当前节点 }
枝节点:
public class Limb:AbstractClass { public Limb() { list = new ArrayList(); } public override void Add(AbstractClass item) { list.Add(item); } public override void Remove(AbstractClass item) { if(list.Contains(item)) list.Remove(item); } public override string Print() { Console.Write(name + " "); if(list.Count != 0) { for(int i = 0;i<list.Count;i++) { Console.Write("(Parent is " + name + ")"); ((AbstractClass)list[i]).Print(); } } return name; } }
叶子节点:
public class Leaf:AbstractClass { public Leaf() { list = null; } public override void Add(AbstractClass item) { } public override void Remove(AbstractClass item) { } public override string Print() { Console.Write(name + ","); return this.name; } }
引用:
static void Main(string[] args) { AbstractClass Tree = new Limb(); GetTree(Tree); PrintTree(Tree); Console.Read(); } public static void GetTree(AbstractClass Tree) { Tree.name = "1"; AbstractClass leaf2 = new Leaf(); leaf2.name = "2"; Tree.Add(leaf2); AbstractClass limb3 = new Limb(); limb3.name = "3"; Tree.Add(limb3); AbstractClass leaf4 = new Leaf(); leaf4.name = "4"; limb3.Add(leaf4); AbstractClass leaf5 = new Leaf(); leaf5.name = "5"; limb3.Add(leaf5); } public static void PrintTree(AbstractClass Tree) { Tree.Print(); }