概述:
將對象組合成樹形結構以表示"部分-整體"的階層。"Composite"使得使用者對單個對象和組合對象的使用具有一致性。
適用場合:
1.你想用部分-整體結構層次。
2.你希望使用者忽略組合對象與單個對象的不同,使用者將統一的使用組合結構中的所有對象。
類圖:
程式碼範例:
1.定義一個組件介面,無論是葉子和樹枝都繼承它。
/// <summary>
/// 為組合中的對象聲明介面,在適當情況下,實現所有類公有介面的的預設行為。
/// 聲明一個介面用於訪問和管理Component的子組件
/// </summary>
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 Display(int depth);
}
2.定義葉子,但是這裡給出了葉子的無意義的add和reomove方法
class Leaf:Component
{
public Leaf(string name):base(name){}
/// <summary>
/// 由於葉子沒增加樹枝的能力,所以add和remove方法實現它是沒有意義的
/// 但這樣可以消除分葉節點和枝節點在抽象層次的區別,他們具備完全一致的介面
/// </summary>
/// <param name="c"></param>
public override void Add(Component c)
{
Console.WriteLine("Cannot add to a Leaf");
}
public override void Remove(Component c)
{
Console.WriteLine("Cannot remove from a leaf"); ;
}
/// <summary>
/// 分葉節點的具體方法,此處顯示其名稱和層級
/// </summary>
/// <param name="depth"></param>
public override void Display(int depth)
{
Console.WriteLine(new String('-',depth)+name);
}
}
3.定義枝節點
/// <summary>
/// 定義有行為的枝節點,用來儲存子組件,在Componet介面中實現與子組件有關的操作,
/// 比如add和remove
/// </summary>
class Composite:Component
{
/// <summary>
/// 一個子物件集合用來儲存其下屬的枝節點和分葉節點
/// </summary>
private List<Component> children = new List<Component>();
public Composite(string name):base(name){}
public override void Add(Component c)
{
children.Add(c);
}
public override void Remove(Component c)
{
children.Remove(c);
}
/// <summary>
/// 顯示其枝節點名稱,並對其下級進行遍曆
/// </summary>
/// <param name="depth"></param>
public override void Display(int depth)
{
Console.WriteLine(new String('-',depth)+name);
foreach(Component ct in children)
{
ct.Display(depth+2);
}
}
}
4,用戶端展示小樹的生長過程
/// <summary>
/// 測試混合模式
/// </summary>
static void TestComposite()
{
///產生樹根,根上長出兩片葉子
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
///根上長出分支X,分支上又長了兩片葉子
Composite comp = new Composite("Composite X");
comp.Add(new Leaf("Leaf XA"));
comp.Add(new Leaf("Leaf XB"));
root.Add(comp);
//分支X上又長出了XY分支,分支上又生了兩片嫩葉
Composite comp2 = new Composite("Composite XY");
comp2.Add(new Leaf("Leaf XYA"));
comp2.Add(new Leaf("Leaf XYB"));
root.Add(comp2);
///根部又長出兩片葉子,但是一個葉子D掉落了
root.Add(new Leaf("Leaf C"));
Leaf leaf = new Leaf("Leaf D");
root.Add(leaf);
root.Remove(leaf);
//從1開始往下遍曆,顯示整個小樹的樣子
root.Display(1);
Console.Read();
}
小結:
在System.Web.UI.Control類裡面就有Add和Remove方法,也是組合模式的經典應用,但是沒有具體查證,希望大家學習的時候能查證一下。