c# 组合模式

组合模式:将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。需求中式体现部分与整体层次的结构时,统一地使用组合对象中的所有对象时,应该考虑使用组合模式

结构图:


抽象对象:

代码如下:

 1     abstract class Component
 2     {
 3         protected string name;
 4         public Component(string name)
 5         {
 6             this.name = name;
 7         }
 8         public abstract void Add(Component c);
 9         public abstract void Remove(Component c);
10         public abstract void Display(int depth);
11     }

无子节点的:

 1     class Leaf : Component
 2     {
 3         public Leaf(string name)
 4             : base(name)
 5         { }
 6         public override void Add(Component c)
 7         {
 8             //throw new NotImplementedException();
 9             Console.WriteLine("Cannot add to a Leaf");
10         }
11         public override void Remove(Component c)
12         {
13             //throw new NotImplementedException();
14             Console.WriteLine("Cannot remove to a Leaf");
15         }
16         public override void Display(int depth)
17         {
18             //throw new NotImplementedException();
19             Console.WriteLine(new string('-', depth) + name);
20         }
21     }

可以有子结点:

代码如下:

 1 class Composite : Component
 2     {
 3         private List<Component> children = new List<Component>();
 4         public Composite(string name)
 5             : base(name)
 6         { }
 7         public override void Add(Component c)
 8         {
 9             //throw new NotImplementedException();
10             children.Add(c);
11         }
12         public override void Remove(Component c)
13         {
14             //throw new NotImplementedException();
15             children.Remove(c);
16         }
17         public override void Display(int depth)
18         {
19             //throw new NotImplementedException();
20             Console.WriteLine(new string('-', depth) + name);
21             foreach (Component component in children)
22             {
23                 component.Display(depth + 2);
24             }
25         }
26     }

主函数调用:

代码如下:

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Composite root = new Composite("root");
 6             root.Add(new Leaf("Leaf A"));
 7             root.Add(new Leaf("Leaf B"));
 8             Composite comp = new Composite("Composite X");
 9             comp.Add(new Leaf("Leaf XA"));
10             comp.Add(new Leaf("Leaf XB"));
11             root.Add(comp);
12             Composite comp2 = new Composite("Composite X");
13             comp2.Add(new Leaf("Leaf XYA"));
14             comp2.Add(new Leaf("Leaf XYB"));
15             comp.Add(comp2);
16             root.Display(1);
17             Console.ReadKey();
18         }
19     }

 

posted @ 2015-01-15 11:18  sirzhang  阅读(297)  评论(0)    收藏  举报
AmazingCounters.com