如果要为已经定义好的类添加新的职责,通常我们会定义一个新类继承自定义好的类。但是,如果职责越累越多,则继承体系会越来越庞大,继承的深度也会越来越深。
而Decorator装饰模式提供了一种给类添加职责的方法,不是通过继承,而是通过组合。
假设现在我们有一个文本框,想用边框和滚动条去装饰。
#include <iostream>
using namespace std;
class Component
{
public:
virtual void show()=0;
virtual ~Component(){}
};
//主体类,被装饰的对象
class TextArea:public Component
{
public:
void show(){cout<<"文本框"<<endl;}
};
//装饰类
class Decorator:public Component
{
public:
Decorator(Component *_com):com(_com){}
void show(){com->show();}
virtual ~Decorator(){}
protected:
Component *com;
};
//用边框装饰
class BorderDecorator:public Decorator
{
public:
BorderDecorator(Component *_com):Decorator(_com){}
void show(){
com->show();
cout<<"用边框装饰"<<endl;
}
};
//用滚动条装饰
class RollDecorator:public Decorator
{
public:
RollDecorator(Component *_com):Decorator(_com){}
void show()
{
com->show();
cout<<"用滚动条装饰"<<endl;
}
};
/*
**如果需要其余装饰,则继承Decorator即可,不必每次都继承与TextArea
*/
int main()
{
//创建一个文本框
TextArea *ta=new TextArea;
//用边框去装饰文本框
BorderDecorator *bd=new BorderDecorator(ta);
//用滚动条去装饰带有边框的文本框
RollDecorator *rd=new RollDecorator(bd);
rd->show();
delete ta;
delete bd;
delete rd;
return 0;
}
![](https://img-my.csdn.net/uploads/201210/24/1351081641_4863.png)