Composite Design Pattern

最近项目中用到了组合模式,自己系统地总结一下该模式:

组合模式(Composite Design Pattern)主要功能是能够使客户端(Client Code) 平等的对待单一组件(Single Componets)和容器组件(Container Componen)。从而实现客户端代码与组件之间的解耦。

从上图可以看出,Client依赖与抽象AComponet,该抽象可以是interface 或abstract类型。Leaf1,leaf2和Composite泛化于AComponent,同是Composite依赖于AComponet。习惯上称像Leaf1和leaf2这样的Single Componet为叶子组件,Composite这样的Container Componet为树枝,AComponet为根(root)。该模式主要用在容器组件递归调用。

下面给出具体例子,我们知道ASP.Net中控件都有Render方法,控件类型有容器类型(Panel,Form)与非容器类型(Button)。下面简单模拟Form显示窗体上所有控件。

首先,定义一个接口IControl,上图中的Root,代码如下:

IControl 
1 namespace ComposityPattern
2 {
3   public interface IControl
4   {
5     void Render();
6   }
7 }

接下来实现Button类,相当于Leaf1

Button
1 namespace ComposityPattern
2 {
3   public class Button : IControl
4   {
5     public void Render()
6     {
7       Console.WriteLine("Button Rended");
8     }
9   }
10 }

实现Form类,相当于Composite类

Form
1 namespace ComposityPattern
2 {
3   public class Form : IControl
4   {
5     private List<IControl> controls = new List<IControl>();
6
7     public void Add(IControl control)
8     {
9        controls.Add(control);
10     }
11
12    public void Remove(IControl control)
13    {
14       controls.Remove(control);
15    }
16
17    public void Render()
18    {
19       Console.WriteLine("Form Rended");
20
21    if(controls!=null)
22    {
23     foreach (var control in controls)
24     {
25       control.Render();
26     }
27    }
28  }
29 }
30 }

Main函数(创建对象可以使用Abstract Factory Pattern)

Main
1 namespace ComposityPattern
2 {
3   class Program
4   {
5     static void Main(string[] args)
6     {
7       Form form = new Form();
8       Button buttonInForm = new Button();
9
10       Console.WriteLine("Container's Render Method excute.");
11       form.Add(buttonInForm);
12          form.Render();
13
14          Console.WriteLine("Single's Render Method excute.");
15          Button button = new Button();
16          button.Render();
17
18          Console.ReadLine();
19        }
20    }
21 }

结果:

Container's Render Method excute.
Form Rended
Button Rended
Single's Render Method excute.
Button Rended

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted @ 2011-03-15 20:16  刘 慧  阅读(330)  评论(0编辑  收藏  举报