关于组合模式的疑惑

13-02-06 anyedage
请问:1、组合模式到底有啥用呢

2、为什么要区分leaf和composite

比如:

namespace MyConApp

{

//1、抽象类Component

public 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<Component> children;

public Composite(string name)

: base(name)

{

if (children == null)

{

children = new List<Component>();

}

}

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完全可以啊

anyedage
2013-02-06 17:55
谁能举一个自己真正用过这个模式的例子?

banq
2013-02-07 20:58
组合模式关键是向客户端隐藏复杂的结构关系。

猜你喜欢