组合模式(Composite)
组合模式:将对象组合成树形结构以表示’部分-整体‘的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

1 namespace Composite//组合模式 2016.12.18 14:18 by ldb
2 {
3 abstract class Component //为组合中的对象声明接口。
4 {
5 protected string name;
6 public Component(string name)
7 {
8 this.name = name;
9 }
10
11 public abstract void Add(Component c);
12 public abstract void Remove(Component c);
13 public abstract void Display(int depht);
14 }
15
16 class Leaf : Component //在组合中表示叶节点对象,叶节点没有子节点。
17 {
18 public Leaf(string name)
19 : base(name)
20 {
21
22 }
23 public override void Add(Component c)
24 {
25 Console.WriteLine("不能 添加枝节点");
26 }
27
28 public override void Remove(Component c)
29 {
30 Console.WriteLine("不能移除枝节点");
31 }
32 public override void Display(int depht)
33 {
34 Console.WriteLine(new string('-',depht) + name);
35 }
36 }
37
38 class Composite : Component
39 {
40 private List<Component> children = new List<Component>();
41 public Composite(string name)
42 : base(name)
43 {
44
45 }
46 public override void Add(Component c)
47 {
48 children.Add(c);
49 }
50 public override void Remove(Component c)
51 {
52 children.Remove(c);
53 }
54 public override void Display(int depht)
55 {
56 Console.WriteLine(new string('-',depht) + name);
57
58 foreach(var com in children)
59 {
60 com.Display(depht);
61 }
62
63 }
64 }
65 class Program
66 {
67 static void Main(string[] args)
68 {
69 Composite root = new Composite("root");//生成树根,根上长出两叶LeafA,LeafB.
70
71 root.Add(new Leaf("LeafA"));
72 root.Add(new Leaf("LeafB"));
73
74 Composite comp = new Composite("Composite X");//根上长出分枝Composite X,分枝上也有两叶Leaf XA,Leaf XB
75
76 comp.Add(new Leaf("Leaf XA"));
77 comp.Add(new Leaf("Leaf XB"));
78
79 root.Add(comp);
80
81 Composite comp2 = new Composite("Composite XY");//在分枝Composite X长出分枝Composite XY,分枝上也有两叶Leaf XYA,Leaf XYB
82
83 comp2.Add(new Leaf("Leaf XYA"));
84 comp2.Add(new Leaf("Leaf XYB"));
85
86 comp.Add(comp);
87
88 root.Display(1);
89
90 Console.Read();
91 }
92 }
93 }

浙公网安备 33010602011771号