定义: 动态地给一个对象添加额外职责,而对客户应用来说则是透明的。
如:给一段文字 加粗或加颜色等动作,对于需要输出这段文字的客户类来说,则是透明的。因为它不需要知道这段文字是否 改变。
VS 2005 下测试通过的代码:
*********************************************************************************
/*
功能:装饰模式:Decorator
时间:2009年8月12日15:47:32
*/
/*
定义一个共同的基类,定义供外部使用的一个借口
*/
class Visualcomponent
{
public:
bool virtual Draw();
};
bool Visualcomponent::Draw()
{
return true;
}
/*
被装饰的类
*/
class Concrete_componect:public Visualcomponent
{
public:
bool Draw();
char *text;
Concrete_componect(char* text);
};
Concrete_componect::Concrete_componect(char *s)
{
text=s;
}
bool Concrete_componect::Draw()
{
cout<<text<<endl;
return true;
}
/*
具体的装饰类的 共同基类。
*/
class Decorator:public Visualcomponent
{
public:
bool Draw();
Decorator(Visualcomponent* comp);
private:
Visualcomponent* vis_comp;
};
Decorator::Decorator(Visualcomponent *comp)
{
vis_comp=comp;
}
bool Decorator::Draw()
{
vis_comp->Draw();
return true;
}
/*
具体装饰类A。
*/
class Decorator_A:public Decorator
{
public:
bool Draw();
void Add_color();
Decorator_A(Visualcomponent *comp):Decorator(comp) {};
};
bool Decorator_A::Draw()
{
this->Add_color();
Decorator::Draw();
return true;
}
void Decorator_A::Add_color()
{
cout<<"已经对此文件添加颜色"<<endl;
}
/*
具体装饰类B
*/
class Decorator_B:public Decorator
{
public:
bool Draw();
void Add_word();
Decorator_B(Visualcomponent *comp):Decorator(comp){};
};
bool Decorator_B::Draw()
{
this->Add_word();
Decorator::Draw();
return true;
}
void Decorator_B::Add_word()
{
cout<<"已经对此文件 添加文字,修改"<<endl;
}
/*
为客户端。
*/
class client
{
public:
void Display(Visualcomponent* V);
};
void client::Display(Visualcomponent *V)
{
V->Draw();
}
int _tmain(int argc, _TCHAR* argv[])
{
char *s="abcdefgh";
Visualcomponent* vc =new Concrete_componect(s);
client c;
c.Display(vc); //未装饰输出
Visualcomponent* v1=new Decorator_A(vc); // 仅对 其 添加颜色,进行装饰。
c.Display(v1);
Visualcomponent* v2=new Decorator_B(vc); //仅对 其 添加文字,进行装饰。
c.Display(v2);
Visualcomponent* v3=new Decorator_B(v1); // 对其 添加颜色及 添加文字,两项装饰。
c.Display(v3); //对其进行装饰与否,对于客户程序(client) 透明使用。
return 0;
}
程序运行结果如下:
abcdefgh
已经对此文件添加颜色
abcdefgh
已经对此文件 添加文字,修改
abcdefgh
已经对此文件 添加文字,修改
已经对此文件添加颜色
abcdefgh