转自http://www.cppblog.com/lwch/archive/2011/05/05/145756.html
装饰模式
前序
制作一个可以给人搭配不同的服饰的系统,比如类似QQ,网络游戏或论坛都有的Avatar系统.
装饰模式
装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案,提供比继承更多的灵活性。动态给一个对象增加功能,这些功能可以再动态的撤消。增加由一些基本功能的排列组合而产生的非常大量的功能。
实现方式(UML类图)
实现代码
#include <stdio.h>
class Person
{
public:
Person() : name(0){}
Person(char* _name) : name(_name){}
virtual void Show()
{
printf("装扮的%s",name);
}
protected:
char* name;
};
class Finery : public Person
{
public:
Finery() : component(0){}
void Decorate(Person* component)
{
this->component = component;
}
virtual void Show()
{
if(component) component->Show();
}
protected:
Person* component;
};
class TShirts : public Finery
{
public:
virtual void Show()
{
printf("大T恤 ");
__super::Show();
}
};
class BigTrouser : public Finery
{
public:
virtual void Show()
{
printf("跨裤 ");
__super::Show();
}
};
class Sneakers : public Finery
{
public:
virtual void Show()
{
printf("破球鞋 ");
__super::Show();
}
};
class Suit : public Finery
{
public:
virtual void Show()
{
printf("西装 ");
__super::Show();
}
};
class Tie : public Finery
{
public:
virtual void Show()
{
printf("领带 ");
__super::Show();
}
};
class LeatherShoes : public Finery
{
public:
virtual void Show()
{
printf("皮鞋 ");
__super::Show();
}
};
int main()
{
Person* xc = new Person("小菜");
printf("第一种装扮:\n");
Sneakers* pqx = new Sneakers();
BigTrouser* kk = new BigTrouser();
TShirts* dtx = new TShirts();
pqx->Decorate(xc);
kk->Decorate(pqx);
dtx->Decorate(kk);
dtx->Show();
printf("\n第二种装扮:\n");
LeatherShoes* px = new LeatherShoes();
Tie* ld = new Tie();
Suit* xz = new Suit();
px->Decorate(xc);
ld->Decorate(px);
xz->Decorate(ld);
xz->Show();
delete xc;
delete pqx;
delete kk;
delete dtx;
delete px;
delete ld;
delete xz;
return 0;
}