1.特色:用樹狀結構表示「總體-部分」的層次關係,使單個對象(葉節點)與組合對象(枝節點)的使用具備一致性。ide
2.概念:將對象組合成樹形結構以表示「部分-總體」的層次結構。組合模式使得用戶對單個對象和組合對象的使用具備一致性。this
3.類圖:component
4.程序實現:對象
/// <summary> /// 一個抽象構件,聲明一個接口用於訪問和管理Component的子部件 /// </summary> public abstract class Component { protected string name; public Component(string name) { this.name = name; } /// <summary> /// 增長一個節點 /// </summary> /// <param name="component"></param> public abstract void Add(Component component); /// <summary> /// 移除一個節點 /// </summary> /// <param name="component"></param> public abstract void Remove(Component component); /// <summary> /// 顯示層級結構 /// </summary> public abstract void Display(int level); } /// <summary> /// 葉子節點 /// </summary> public class Leaf : Component { public Leaf(string name) : base(name) { } /// <summary> /// 因爲葉子節點沒有子節點,因此Add和Remove方法對它來講沒有意義,但它繼承自Component,這樣作能夠消除葉節點和枝節點對象在抽象層次的區別,它們具有徹底一致的接口。 /// </summary> /// <param name="component"></param> public override void Add(Component component) { Console.WriteLine("Can not add a component to a leaf."); } /// <summary> /// 實現它沒有意義,只是提供了一個一致的調用接口 /// </summary> /// <param name="component"></param> public override void Remove(Component component) { Console.WriteLine("Can not remove a component to a leaf."); } public override void Display(int level) { Console.WriteLine(new string('-',level) + name); } } /// <summary> /// 定義有枝節點的行爲,用來存儲部件,實如今Component接口中對子部件有關的操做 /// </summary> public class Composite : Component { public Composite(string name) : base(name) { } /// <summary> /// 一個子對象集合,用來存儲其下屬的枝節點和葉節點 /// </summary> private List<Component> children = new List<Component>(); /// <summary> /// 增長子節點 /// </summary> /// <param name="component"></param> public override void Add(Component component) { children.Add(component); } /// <summary> /// 移除子節點 /// </summary> /// <param name="component"></param> public override void Remove(Component component) { children.Remove(component); } public override void Display(int level) { Console.WriteLine(new string('-', level) + name); // 遍歷其子節點並顯示 foreach (Component component in children) { component.Display(level+2); } } } class Program { static void Main(string[] args) { // 生成樹根,併爲其增長兩個葉子節點 Component root = new Composite("Root"); root.Add(new Leaf("Leaf A in Root")); root.Add(new Leaf("Leaf B in Root")); // 爲根增長兩個枝節點 Component branchX = new Composite("Branch X in Root"); Component branchY = new Composite("Branch Y in Root"); root.Add(branchX); root.Add(branchY); // 爲BranchX增長頁節點 branchX.Add(new Leaf("Leaf A in Branch X")); // 爲BranchX增長枝節點 Component branchZ = new Composite("Branch Z in Branch X"); branchX.Add(branchZ); // 爲BranchY增長葉節點 branchY.Add(new Leaf("Leaf in Branch Y")); // 爲BranchZ增長葉節點 branchZ.Add(new Leaf("Leaf in Branch Z")); // 顯示樹 root.Display(1); Console.Read(); } }