C++实现装饰者模式

来源:互联网 发布:淘宝折叠雨伞 编辑:程序博客网 时间:2024/05/22 00:30
/*装饰者模式:动态的给一些对象增加一些额外的功能,就增加功能来说,装饰着模式比生成子类更加灵活*/#include <iostream>using namespace std;class Component{public:virtual void diplay() = 0;};class ConcreteComponent: public Component{public:virtual void diplay(){cout<<" i am a person "<<endl;}};class Decorator: public Component{protected:Component* base;int type;public:void SetCompoenet(Component *base){this->base = base;}void diplay(){cout<<"begin to decorate...."<<endl;base->diplay();}};class Decorator1: public Decorator{public:Decorator1(){type = 1;}void diplay(){cout<<"i am decorator1 ."<< type <<endl;base->diplay();}};class Decorator2: public Decorator{public:Decorator2(){type = 2;}void diplay(){cout<<"i am decorator2 ."<<type<<endl;base->diplay();}};int main(){ConcreteComponent *component  = new ConcreteComponent;Decorator1        *decorator1 = new Decorator1;Decorator2        *decorator2 = new Decorator2;decorator1->SetCompoenet(component);decorator2->SetCompoenet(decorator1);decorator2->diplay();system("pause");return 0;}