[设计模式学习-C++实现]--Decorator模式

Decorator模式(装饰者模式):有时候我们想为已有的类添加一些新的职责,可以通过新建一个类继承已有的类。但是这样不仅类的数量会增加,而且继承的深度也会增加,代码会更加复杂。装饰者模式就可以更加好的解决此类问题。

其中ConcreteComponent和Decorator类都有共同的基类Component。当然可以让Decorator直接拥有一个指向ConcreteComponent的引用或指针也可以达到同样的效果。但是这样做并不好,如果新添加一个ConreteComponent就需要修改Decorator。而用如上的设计,无论添加多少个ConcretorComponent,都不需要改变Decorator。

Deractor模式具体代码实现(来自《GOF23种设计模式详解》一书):

 1 //Decora tor. h 
 2 #ifndef _DECORATOR_H_ 
 3 #define _DECORA TOR_H_ 
 4 class Componen t  
 5 { 
 6 public: 
 7  virtual ~Component(); 
 8   virtual  void  Operation(); 
 9 protected: 
10  Component(); 
11 private: 
12 };
13 
14 //Decora tor. cpp 
15 #include  "Decora tor. h" 
16 #include  <iostream> 
17 Com ponent::Component() 
18 { 
19 } 
20 Com ponent::~Component() 
21 {   } 
22 void Component::Operation() 
23 {   } 
Decorator
 1 //ConreteComponent.h
 2 class ConcreteComponent:public Component 
 3 { 
 4 public: 
 5  ConcreteComponent(); 
 6  ~ConcreteComponent(); 
 7   void  Operation (); 
 8 protected: 
 9 private: 
10 };
11 
12 //ConreteComponent.cpp
13 Concrete Com ponent::Con creteC omponent() 
14 {   } 
15 Concrete Com ponent::~Conc reteCom ponent() 
16 {   } 
17 void Concre teCo mponent::Operati on() 
18 { 
19  std::cout<<"Conc reteComponent 
20 operation..."<<std::endl; 
21 }
ConcreteComponent
 1 //Decorator.h
 2 class Decorator :public Component 
 3 { 
 4 public: 
 5  Decorator(Component*  com); 
 6  virtual ~Decor a tor(); 
 7   void  Operation (); 
 8 protected: 
 9  Component* _com; 
10 private: 
11 };
12 
13 //Decorator .cpp
14 Decorator::Deco r ator(Component * com) 
15 { 
16   this->_com  =  com;  
17 } 
18 Decorator::~Decorator() 
19 { 
20  delete  _c om; 
21 } 
22 void Decora tor: :Operation() 
23 {  }
Decorator
 1 //ConcreteDecorator.h
 2 class ConcreteDecorator:public  Decorator 
 3 { 
 4 public: 
 5  ConcreteDecora tor(Component*  com); 
 6  ~ConcreteDecor a tor(); 
 7   void  Operation (); 
 8  void AddedBehavior(); 
 9 protected: 
10 private: 
11 }; 
12 
13 //ConcreteDecorator.cpp
14 ConcreteDecora tor::Concre teDecorator(Compo
15 nent* com):Decorator(com) 
16 {   } 
17 ConcreteDecora tor::~ConcreteDecorator() 
18 {   } 
19 void Concre teD ecorator ::AddedB ehavior() 
20 { 
21  std::cout<<"Conc reteDecor a tor::AddedBe
22 hacior.. .. "<<std: :e ndl; 
23 } 
24 void Concre teD ecorator ::Oper a tion() 
25 { 
26  _com->Operation(); 
27  this->AddedBehavior(); 
28 }
ConcreteDecorator
 1 //main.cpp 
 2  
 3 #include  "Decorator. h" 
 4 #include  <iostream> 
 5 using namespace std; 
 6  
 7 int main( i nt ar gc,char* argv[] )  
 8 { 
 9   Component* com = new ConcreteComponent(); 
10   Decorator* dec = new  ConcreteDecora tor(com); 
11  
12  dec->Opera tion( ); 
13  
14  delete  de c;  
15  
16  return 0;  
17 }
main

也分享一个自己写的代码吧,vs2012环境下写的,实现一个做冰淇淋的机器,用装饰者模式。
http://pan.baidu.com/share/link?shareid=500729&uk=4246870181

 

 

posted @ 2013-05-26 21:26  mengmee  阅读(210)  评论(0编辑  收藏  举报