设计模式 装饰者模式(Decorator)

意图

  动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。

适用性

  1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。 

  2.处理那些可以撤消的职责。 

  3.当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。  

结构图

Code

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



人生如棋、我愿为卒、行动虽缓、从未退过

原文地址:https://www.cnblogs.com/sunjinpeng/p/2433560.html