装饰者模式

抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。

具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。

装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。

具体装饰(Concrete Decorator)角色:负责给构件对象"贴上"附加的责任。

 1 class Component
 2 {
 3 public:
 4     virtual void Draw();         
 5 }
 6 
 7 class ConcreteComponent : Component
 8 {
 9 public:
10     void Draw()
11     {
12                  
13      }        
14 }
15 
16 abstract class Decorator : Component
17 {
18 protected:  
19     Component* ActualComponent ;  
20 public:  
21      Decorator(Component*   ActualComponent)
22     {
23       this->ActualComponent =ActualComponent ; 
24     }  
25     void Draw()
26     {
27          if (ActualComponent != null)
28              ActualComponent.Draw();        
29     }
30 }
31 
32 class ConcreteDecorator : Decorator 
33 {
34 public:
35     ConcreteDecorator (Component*   ActualComponent):   Decorator (ActualComponent) {}  
36     void Draw()
37         {
38             CustomDecoration();
39             ActualComponent->Draw();
40         }
41         void CustomDecoration()
42         {
43             .............
44         }
45 }
46 
47 int Main()
48 {
49     Component* c = new ConcreteComponent();
50 
51     Decorator*  d = new ConcreteDecorator(c);
52     d->Draw();             
54     return 0;
55 
56 }   

总结:
其可以一层层的嵌套上去,就是有秩序的装饰你的东西。 如上面的代码main中:
Decorator*  d = new ConcreteDecorator(c);
Decorator*  e = new ConcreteDecorator_A(d);
Decorator*  f = new ConcreteDecorator_B(e);
............................

 

posted @ 2013-07-10 22:32  风啊  阅读(135)  评论(0)    收藏  举报