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,代码如下:

ContractedBlock.gif ExpandedBlockStart.gifIControl  
1 namespace ComposityPattern
2 {
3    public interface IControl
4    {
5      void Render();
6    }
7 }

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

ContractedBlock.gif ExpandedBlockStart.gif 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类

ContractedBlock.gif ExpandedBlockStart.gif 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)

ContractedBlock.gif ExpandedBlockStart.gif 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

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

转载于:https://www.cnblogs.com/philwiki/articles/1985289.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值