装饰者模式(Decorator Pattern)
装饰者模式(Decorator Pattern):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式比生成子类更加灵活。
1 #ifndef DECORATOR_H 2 #define DECORATOR_H 3 4 #include<iostream> 5 using namespace std; 6 7 class Component 8 { 9 public: 10 virtual void operation()=0; 11 }; 12 13 class ConcreteComponent:public Component 14 { 15 public: 16 void operation() 17 { 18 cout<<"ConcreteComponent:operation()"<<endl; 19 } 20 }; 21 22 class Decorator:public Component 23 { 24 protected: 25 Component* wappedObj; 26 public: 27 Decorator(Component* component){ 28 wappedObj=component; 29 } 30 }; 31 32 class ConcreteDecoratorA:public Decorator 33 { 34 public: 35 ConcreteDecoratorA(Component* component):Decorator(component){} 36 37 void operation() 38 { 39 wappedObj->operation(); 40 cout<<"ConcreteDecoratorA:operation()"<<endl; 41 } 42 }; 43 44 class ConcreteDecoratorB:public Decorator 45 { 46 public: 47 ConcreteDecoratorB(Component* component):Decorator(component){} 48 49 void operation() 50 { 51 wappedObj->operation(); 52 cout<<"ConcreteDecoratorB:operation()"<<endl; 53 } 54 }; 55 56 #endif//DECORATOR_H 57 58 int main() 59 { 60 61 Component* component=new ConcreteComponent(); 62 component->operation(); 63 cout<<endl; 64 65 component=new ConcreteDecoratorB(component); 66 component->operation(); 67 cout<<endl; 68 69 component=new ConcreteDecoratorA(component); 70 component->operation(); 71 cout<<endl; 72 73 return 0; 74 }