組合是一種結構型設計模式, 你可使用它將對象組合成樹狀結構, 而且能像使用獨立對象同樣使用它們。設計模式
組合模式(Composite Pattern)是將對象組合成樹形結構以表示‘部分-總體’的層次結構。組合模式使得用戶對單個對象和組合對象的使用具備一致性。安全
對於絕大多數須要生成樹狀結構的問題來講, 組合模式都是很是好的一種解決方案。 主要的功能是在整個樹狀結構上遞歸調用方法並對結果進行彙總。ide
組合模式實現的最關鍵的地方是——簡單對象和複合對象必須實現相同的接口。這就是組合模式可以將組合對象和簡單對象進行一致處理的緣由。this
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Composite { class Program { static void Main(string[] args) { // 建立根節點 Composite root = new Composite("root"); root.add(new Leaf("Leaf A")); root.add(new Leaf("Leaf B")); // 建立第二層節點 Composite branch = new Composite("branch"); branch.add(new Leaf("branch BX")); branch.add(new Leaf("branch BY")); root.add(branch); // 建立第三層節點 Composite branch2 = new Composite("branch2"); branch2.add(new Leaf("branch2 BBX")); branch2.add(new Leaf("branch2 BBY")); root.add(branch2); // 葉子節點操做 Composite branch3 = new Composite("branch3"); Leaf leaf = new Leaf("Leaf L"); Leaf leaf1 = new Leaf("Leaf L1"); leaf.add(leaf1); leaf.delete(leaf1); branch3.add(leaf); branch3.add(leaf1); branch3.delete(leaf); root.add(branch3); // 顯示 root.show(1); Console.Read(); } } /// <summary> /// 抽象構件 /// </summary> public abstract class Component { public string Name { get; set; } public Component(string name) { this.Name = name; } // 添加一個葉子構件或樹枝構件 public abstract void add(Component component); // 刪除一個葉子構件或樹枝構件 public abstract void delete(Component component); // 獲取分支下的全部葉子構件和樹枝構件 public abstract void show(int depth); } /// <summary> /// 葉子構件 /// </summary> public class Leaf : Component { public Leaf(string name):base(name) { } // 若是是葉子節點,則不容許進行添加節點,由於葉子節點下再沒有節點了 public override void add(Component component) { Console.WriteLine("葉子節點不能添加其餘內容"); } // 若是是葉子節點,則不容許進行刪除節點,由於葉子節點下再沒有節點了 public override void delete(Component component) { Console.WriteLine("葉子節點不能刪除內容"); } public override void show(int depth) { // 輸出葉子節點 for (int i = 0; i < depth; i++) { Console.Write("-"); } Console.WriteLine(this.Name); } } /// <summary> /// 樹構件 /// </summary> public class Composite : Component { protected List<Component> _children = new List<Component>(); public Composite(string name) : base(name) { } public override void add(Component component) { _children.Add(component); } public override void delete(Component component) { _children.Remove(component); } public override void show(int depth) { // 輸出樹形結構層次 for (int i=0; i<depth; i++) { Console.Write("-"); } Console.WriteLine(this.Name); // 向下遍歷 foreach (Component compontent in _children) { compontent.show(depth + 1); } } } }
運行後結果:spa
葉子節點不能添加其餘內容 葉子節點不能刪除內容 -root --Leaf A --Leaf B --branch ---branch BX ---branch BY --branch2 ---branch2 BBX ---branch2 BBY --branch3 ---Leaf L1
優勢:設計
缺點:code