装饰模式(Decorator),动态的给一个对象添加一些额外的职责,先看图
Component是定义一个对象接口,可以给这些对象动态的添加职责。
ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。
Decorator装饰类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的
至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能
下面是具体的实现:
- //component.h
- #ifndef AFX_CLASS_COMPONENT
- #define AFX_CLASS_COMPONENT
- class Component
- {
- public:
- virtual void Operation()=0;
- };
- #endif
- #ifndef AFX_CLASS_CONCRETECOMPONENT
- #define AFX_CLASS_CONCRETECOMPONENT
- class ConcreteComponent:public Component
- {
- public:
- virtual void Operation()
- {
- cout<<"具体对象的操作"<<endl;
- }
- };
- #endif
- #ifndef AFX_CLASS_DECORATOR
- #define AFX_CLASS_DECORATOR
- class Decorator:public Component
- {
- public:
- void SetComponent(Component *component)
- {
- this->component = component;
- }
- virtual void Operation()
- {
- if( component != NULL )
- {
- component->Operation();
- }
- }
- protected:
- Component *component;
- };
- #endif
- #ifndef AFX_CLASS_CONCRETEDECORATOR
- #define AFX_CLASS_CONCRETEDECORATOR
- class ConcreteDecoratorA:public Decorator
- {
- public:
- virtual void Operation()
- {
- Decorator::Operation();
- addedState = "New state" ;
- cout<<"具体装饰对象A的操作"<<endl;
- }
- private:
- string addedState;
- };
- class ConcreteDecoratorB:public Decorator
- {
- public:
- virtual void Operation()
- {
- Decorator::Operation();
- AddedBehavior();
- cout<<"具体装饰对象B的操作"<<endl;
- }
- private:
- void AddedBehavior()
- {
- }
- };
- #endif
接着是调用:
- #include <iostream>
- #include <string>
- #include <conio.h>
- using namespace std;
- #include "component.h"
- int main(int argc,char *argv[])
- {
- ConcreteComponent *c = new ConcreteComponent();
- ConcreteDecoratorA *d1 = new ConcreteDecoratorA();
- ConcreteDecoratorB *d2 = new ConcreteDecoratorB();
- d1->SetComponent( c );
- d2->SetComponent( d1 );
- d2->Operation();
- getch();
- return 1;
- }