裝飾模式
前序
制作一個可以給人搭配不同的服飾的系統,比如類似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;
}
運行結果



