码迷,mamicode.com
首页 > 其他好文 > 详细

结构型设计模式之装饰模式

时间:2015-07-17 08:24:01      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

结构 技术分享
意图 动态地给一个对象添加一些额外的职责。就增加功能来说,D e c o r a t o r 模式相比生成子类更为灵活。
适用性
  • 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
  • 处理那些可以撤消的职责。
  • 当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

 

技术分享
 1 using System;
 2 
 3     abstract class Component
 4     {
 5         public abstract void Draw();         
 6     }
 7 
 8     class ConcreteComponent : Component
 9     {
10         private string strName;
11         public ConcreteComponent(string s)
12         {
13             strName = s;            
14         }
15 
16         public override void Draw()
17         {
18             Console.WriteLine("ConcreteComponent - {0}", strName);            
19         }        
20     }
21 
22     abstract class Decorator : Component
23     {
24         protected Component ActualComponent;
25 
26         public void SetComponent(Component c)
27         {
28             ActualComponent = c;
29         }
30         public override void Draw()
31         {
32             if (ActualComponent != null)
33                 ActualComponent.Draw();        
34         }
35     }
36 
37     class ConcreteDecorator : Decorator 
38     {
39         private string strDecoratorName;
40         public ConcreteDecorator (string str)
41         {
42             // how decoration occurs is localized inside this decorator
43             // For this demo, we simply print a decorator name
44             strDecoratorName = str; 
45         }
46         public override void Draw()
47         {
48             CustomDecoration();
49             base.Draw();
50         }
51         void CustomDecoration()
52         {
53             Console.WriteLine("In ConcreteDecorator: decoration goes here");
54             Console.WriteLine("{0}", strDecoratorName);
55         }
56     }
57 
58     
59     /// <summary>
60     ///    Summary description for Client.
61     /// </summary>
62     public class Client
63     {
64         Component Setup() 
65         {
66             ConcreteComponent c = new ConcreteComponent("This is the real component");
67 
68             ConcreteDecorator d = new ConcreteDecorator("This is a decorator for the component");
69 
70             d.SetComponent(c);
71 
72             return d;
73         }
74         
75         public static int Main(string[] args)
76         {
77             Client client = new Client();
78             Component c = client.Setup();    
79 
80             // The code below will work equally well with the real component, 
81             // or a decorator for the component
82 
83             c.Draw();
84             
85             return 0;
86         }
87     }
装饰模式

 

结构型设计模式之装饰模式

标签:

原文地址:http://www.cnblogs.com/ziranquliu/p/4653402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!