1.Decorator 模式通过组合的方式提供了一种给类增加职责(操作)的方法。
2.Decorator模式结构图
3.实现
1 #ifndef _DECORATOR_H_ 2 #define _DECORATOR_H_ 3 4 class Component 5 { 6 public: 7 virtual ~Component(); 8 virtual void Operation(); 9 protected: 10 Component(); 11 private: 12 }; 13 14 class ConcreteComponent:public Component 15 { 16 public: 17 ConcreteComponent(); 18 ~ConcreteComponent(); 19 void Operation(); 20 protected: 21 private: 22 }; 23 24 class Decorator:public Component 25 { 26 public: 27 Decorator(Component* com); 28 virtual ~Decorator(); 29 void Operation(); 30 protected: 31 Component* _com; 32 private: 33 }; 34 35 class ConcreteDecorator:public Decorator 36 { 37 public: 38 ConcreteDecorator(Component* com); 39 ~ConcreteDecorator(); 40 void Operation(); 41 void AddedBehavior(); 42 protected: 43 private: 44 }; 45 46 #endif
1 #include "Decorator.h" 2 #include <iostream> 3 4 Component::Component() 5 { 6 7 } 8 Component::~Component() 9 { 10 11 } 12 void Component::Operation() 13 { 14 15 } 16 ConcreteComponent::ConcreteComponent() 17 { 18 19 } 20 ConcreteComponent::~ConcreteComponent() 21 { 22 23 } 24 void ConcreteComponent::Operation() 25 { 26 std::cout<<"ConcreteComponent operation..."<<std::endl; 27 } 28 Decorator::Decorator(Component* com) 29 { 30 this->_com = com; 31 } 32 Decorator::~Decorator() 33 { 34 delete _com; 35 } 36 void Decorator::Operation() 37 { 38 39 } 40 ConcreteDecorator::ConcreteDecorator(Component*com):Decorator(com) 41 { 42 43 } 44 ConcreteDecorator::~ConcreteDecorator() 45 { 46 47 } 48 void ConcreteDecorator::AddedBehavior() 49 { 50 std::cout<<"ConcreteDecorator::AddedBehacior...."<<std::endl; 51 } 52 void ConcreteDecorator::Operation() 53 { 54 _com->Operation(); 55 this->AddedBehavior(); 56 }
1 //main.cpp 2 #include "Decorator.h" 3 #include <iostream> 4 using namespace std; 5 6 int main(int argc,char* argv[]) 7 { 8 Component* com = new ConcreteComponent(); 9 Decorator* dec = new ConcreteDecorator(com); 10 dec->Operation(); 11 delete dec; 12 return 0; 13 }
4.Decorator模式的讨论
为了多态,通过父类指针指向其具体子类,但是这就带来另外一个问题,当具体子类要添加新的职责,就必须向其父类添加一个这个职责的抽象接口,否则是通过父类指针是调用不到这个方法了。这样处于高层的父类就承载了太多的特征(方法),并且继承自这个父类的所有子类都不可避免继承了父类的这些接口,但是可能这并不是这个具体子类所需要的。而在Decorator模式提供了一种较好的解决方法,当需要添加一个操作的时候就可以通过Decorator模式来解决,你可以一步步添加新的职责。