關於組合模式的疑惑

anyedage發表於2013-02-06
請問: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完全可以啊

相關文章