码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-04-27 22:01:49      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:pac   []   ddb   ted   ati   root   out   img   class   

技术分享

 

  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.....

 

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

标签:pac   []   ddb   ted   ati   root   out   img   class   

原文地址:http://www.cnblogs.com/070412-zwc/p/6777284.html

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