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




1 namespace Decorator
2 {
3 //装饰模式 - 2017.08.26 21:32 added by ldb
4
5 abstract class Component
6 {
7 public abstract void Operation();
8 }
9
10 class ConcreateComponet : Component
11 {
12 public override void Operation()
13 {
14 Console.WriteLine("具体对象操作!");
15 }
16 }
17
18 abstract class Decorator : Component
19 {
20 protected Component component = null;
21
22 public void setComponent(Component component)
23 {
24 this.component = component;
25 }
26 public override void Operation()//重写Operation(),实际执行的是Component的重写Operation().
27 {
28 if (component != null)
29 {
30 component.Operation();
31 }
32 }
33 }
34
35 class ConcreateDecoratorA : Decorator
36 {
37 private string addstate;//该类都有的功能,以区别ConcreateDecoratorB类
38 public override void Operation()
39 {
40 base.Operation();//先运行Component的Operation(),再执行该类的addstate功能,相当对应对原Component进行了装饰。
41 addstate = "new state";
42 Console.WriteLine("具体装饰对象A的操作:"+addstate);
43
44 }
45 }
46
47 class ConcreateDecoratorB : Decorator
48 {
49 public override void Operation()
50 {
51 base.Operation();//先运行Component的Operation(),再执行该类的AddedBehavior()功能,相当对应对原Component进行了装饰。
52 AddedBehavior();
53 Console.WriteLine("具体装饰对象B的操作!");
54 }
55
56 private void AddedBehavior()//该类都有的方法,区别于A类。
57 {
58 Console.WriteLine("B类干点其他的事情!");
59 }
60 }
61 class Program
62 {
63 static void Main(string[] args)
64 {
65 ConcreateComponet c = new ConcreateComponet();
66 ConcreateDecoratorA A = new ConcreateDecoratorA();
67 ConcreateDecoratorB B = new ConcreateDecoratorB();
68
69 A.setComponent(c);//装饰的方法是:首先用ConcreateComponet实例化对象c,然后用ConcreateDecoratorA的实例化对象A来包装c,
70 B.setComponent(A);//再用ConcreateDecoratorB的实例化包装A,最后执行B的Operation().
71 B.Operation();
72
73 //其实就是通过子类来对父类进行不同的需求扩展。
74 Console.ReadKey();
75 }
76 }
77 }


浙公网安备 33010602011771号