请问:1、组合模式到底有什么用,谁能举一个自己真正用过这个模式的例子?2、为什么要区分leaf和composite比如:
namespace MyConApp{//1、抽象类Componentpublic abstract class Component{protected string name;
public Component(string name){this.name = name;}
public abstract void Add(Component c);public abstract void Remove(Component c);public abstract void Diaplay(int depth);}
////2、叶子节点Leaf 继承于Component//public class Leaf : Component//{
// public Leaf(string name)// : base(name)// {// }
// public override void Add(Component c)// {// Console.WriteLine("不能向叶子节点添加子节点");// }
// public override void Remove(Component c)// {// Console.WriteLine("叶子节点没有子节点");// }
// public override void Diaplay(int depth)// {// Console.WriteLine(new string('-', depth) + name);// }//}
//3、组合类Composite继承于Component,拥有枝节点行为public class Composite : Component{
List children;
public Composite(string name): base(name){if (children == null){children = new List();}}
public override void Add(Component c){this.children.Add(c);}
public override void Remove(Component c){this.children.Remove(c);}
public override void Diaplay(int depth){Console.WriteLine(new String('-', depth) + name);foreach (Component component in children){component.Diaplay(depth + 2);}}}public class Test{public static void t(){
Composite root = new Composite("根节点root");root.Add(new Composite("根上生出的叶子A"));root.Add(new Composite("根上生出的叶子B"));
Composite comp = new Composite("根上生出的分支CompositeX");comp.Add(new Composite("分支CompositeX生出的叶子LeafXA"));comp.Add(new Composite("分支CompositeX生出的叶子LeafXB"));
root.Add(comp);
Composite comp2 = new Composite("分支CompositeX生出的分支CompositeXY");comp2.Add(new Composite("分支CompositeXY生出叶子LeafXYA"));comp2.Add(new Composite("分支CompositeXY生出叶子LeafXYB"));
comp.Add(comp2);
root.Add(new Composite("根节点生成的叶子LeafC"));Composite leafD = new Composite("leaf D");root.Add(leafD);root.Remove(leafD);root.Diaplay(1);Console.Read();}}}
可以看出,不用Leaf完全可以啊,为什么要区分leaf和composite呢?
- 2 回答
- 0 关注
- 361 浏览
添加回答
举报
0/150
提交
取消