Fork me on GitHub

设计模式——装饰器模式(C++实现)

 

  1 #include <iostream>
  2 #include <string>
  3 
  4 using namespace std;
  5 
  6 class Component
  7 {
  8 public:
  9         virtual void operation() = 0;
 10 };
 11 
 12 class ConcreteComponentA: public Component
 13 {
 14 public:
 15         virtual void operation()
 16         {
 17                 cout<< "ConcreteComponentA....."<< endl;
 18         }
 19 };
 20 
 21 class ConcreteComponentB: public Component
 22 {
 23 public:
 24         virtual void operation()
 25         {
 26                 cout<< "ConcreteComponentB....."<< endl;
 27         }
 28 };
 29 
 30 class Decorator:public Component
 31 {
 32 public:
 33         Decorator(Component* pCom):component(pCom){}
 34 
 35         virtual void operation() = 0;
 36 
 37         Component* component;
 38 };
 39 
 40 class ConcreteDecoratorA: public Decorator
 41 {
 42 public:
 43         ConcreteDecoratorA(Component* pCom):Decorator(pCom){}
 44 
 45         void operation()
 46         {
 47                 component->operation();
 48                 AddBehavior();
 49         }
 50 
 51         void AddBehavior()
 52         {
 53                 cout<< "ConcreteDecoratorA....."<< endl;
 54         }
 55 };
 56 
 57 class ConcreteDecoratorB: public Decorator
 58 {
 59 public:
 60         ConcreteDecoratorB(Component* pCom):Decorator(pCom){}
 61 
 62         void operation()
 63         {
 64                 component->operation();
 65                 AddBehavior();
 66         }
 67 
 68         void AddBehavior()
 69         {
 70                 cout<< "ConcreteDecoratorB....."<< endl;
 71         }
 72 };
 73 
 74 int main(int argc, char* argv[])
 75 {
 76         ConcreteComponentB* ccB = new ConcreteComponentB();
 77 
 78         ConcreteDecoratorA* cdA1 = new ConcreteDecoratorA(ccB);
 79 
 80         ConcreteDecoratorA* cdA2 = new ConcreteDecoratorA(cdA1);
 81 
 82         ConcreteDecoratorB* cdB1 = new ConcreteDecoratorB(cdA1);
 83 
 84         cdA1->operation();cout<< endl;
 85         cdA2->operation();cout<< endl;
 86         cdB1->operation();cout<< endl;
 87 
 88         return 0;
 89 }
 90 
 91 ///////////////////////////
 92 [root]$ ./decorator                   
 93 ConcreteComponentB.....
 94 ConcreteDecoratorA.....
 95 
 96 ConcreteComponentB.....
 97 ConcreteDecoratorA.....
 98 ConcreteDecoratorA.....
 99 
100 ConcreteComponentB.....
101 ConcreteDecoratorA.....
102 ConcreteDecoratorB.....

 

posted @ 2017-04-27 21:40  码农的逼格  阅读(357)  评论(0编辑  收藏  举报