结构型设计模式之组合模式(Composite)
结构 | ![]() |
意图 | 将对象组合成树形结构以表示“部分-整体”的层次结构。C o m p o s i t e 使得用户对单个对象和组合对象的使用具有一致性。 |
适用性 |
|
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections; 3 4 abstract class Component 5 { 6 protected string strName; 7 8 public Component(string name) 9 { 10 strName = name; 11 } 12 13 abstract public void Add(Component c); 14 15 public abstract void DumpContents(); 16 17 // other operations for delete, get, etc. 18 } 19 20 class Composite : Component 21 { 22 private ArrayList ComponentList = new ArrayList(); 23 24 public Composite(string s) : base(s) {} 25 26 override public void Add(Component c) 27 { 28 ComponentList.Add(c); 29 } 30 31 public override void DumpContents() 32 { 33 // First dump the name of this composite node 34 Console.WriteLine("Node: {0}", strName); 35 36 // Then loop through children, and get then to dump their contents 37 foreach (Component c in ComponentList) 38 { 39 c.DumpContents(); 40 } 41 } 42 } 43 44 class Leaf : Component 45 { 46 public Leaf(string s) : base(s) {} 47 48 override public void Add(Component c) 49 { 50 Console.WriteLine("Cannot add to a leaf"); 51 } 52 53 public override void DumpContents() 54 { 55 Console.WriteLine("Node: {0}", strName); 56 } 57 } 58 59 /// <summary> 60 /// Summary description for Client. 61 /// </summary> 62 public class Client 63 { 64 Component SetupTree() 65 { 66 // here we have to create a tree structure, 67 // consisting of composites and leafs. 68 Composite root = new Composite("root-composite"); 69 Composite parentcomposite; 70 Composite composite; 71 Leaf leaf; 72 73 parentcomposite = root; 74 composite = new Composite("first level - first sibling - composite"); 75 parentcomposite.Add(composite); 76 leaf = new Leaf("first level - second sibling - leaf"); 77 parentcomposite.Add(leaf); 78 parentcomposite = composite; 79 composite = new Composite("second level - first sibling - composite"); 80 parentcomposite.Add(composite); 81 composite = new Composite("second level - second sibling - composite"); 82 parentcomposite.Add(composite); 83 84 // we will leaf the second level - first sibling empty, and start 85 // populating the second level - second sibling 86 parentcomposite = composite; 87 leaf = new Leaf("third level - first sibling - leaf"); 88 parentcomposite.Add(leaf); 89 90 leaf = new Leaf("third level - second sibling - leaf"); 91 parentcomposite.Add(leaf); 92 composite = new Composite("third level - third sibling - composite"); 93 parentcomposite.Add(composite); 94 95 return root; 96 } 97 98 public static int Main(string[] args) 99 { 100 Component component; 101 Client c = new Client(); 102 component = c.SetupTree(); 103 104 component.DumpContents(); 105 return 0; 106 } 107 }