您的位置:首页 > 其它

装饰者模式(Decorator Pattern)

2012-06-25 13:53 225 查看
装饰者模式(Decorator Pattern):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式比生成子类更加灵活。



#ifndef DECORATOR_H
#define DECORATOR_H

#include<iostream>
using namespace std;

class Component
{
public:
virtual void operation()=0;
};

class ConcreteComponent:public Component
{
public:
void operation()
{
cout<<"ConcreteComponent:operation()"<<endl;
}
};

class Decorator:public Component
{
protected:
Component* wappedObj;
public:
Decorator(Component* component){
wappedObj=component;
}
};

class ConcreteDecoratorA:public Decorator
{
public:
ConcreteDecoratorA(Component* component):Decorator(component){}

void operation()
{
wappedObj->operation();
cout<<"ConcreteDecoratorA:operation()"<<endl;
}
};

class ConcreteDecoratorB:public Decorator
{
public:
ConcreteDecoratorB(Component* component):Decorator(component){}

void operation()
{
wappedObj->operation();
cout<<"ConcreteDecoratorB:operation()"<<endl;
}
};

#endif//DECORATOR_H

int main()
{

Component* component=new ConcreteComponent();
component->operation();
cout<<endl;

component=new ConcreteDecoratorB(component);
component->operation();
cout<<endl;

component=new ConcreteDecoratorA(component);
component->operation();
cout<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: