针对的问题
1)需要扩展一个类的功能,或给一个类增加附加责任。
2)需要动态的给一个对象增加功能,这些功能可以再动态地撤销。
UML
代码
#include<iostream>
using namespace std;
class person
{
public:
void show()
{
cout<<"出门穿衣服"<<endl;
}
};
class decorate:public person
{
public:
virtual void set(person *p)=0;
private:
person *p;
};
class ClothesRed:public decorate
{
public:
void set(person *p)
{
this->CRed = p;
CRed->show();
cout<<"红衣服"<<endl;
}
private:
person *CRed;
};
class ClothesBlue:public decorate
{
public:
void set(person *p)
{
this->CBlue = p;
CBlue->show();
cout<<"蓝衣服"<<endl;
}
private:
person *CBlue;
};
class PantRed:public decorate
{
public:
void set(person *p)
{
this->PRed = p;
PRed->show();
cout<<"红裤子"<<endl;
}
private:
person *PRed;
};
class PantBlue:public decorate
{
public:
void set(person *p)
{
this->PBlue = p;
PBlue->show();
cout<<"蓝裤子"<<endl;
}
private:
person *PBlue;
};
int main()
{
person *p = new person;
decorate *cred = new ClothesRed;
decorate *cblue = new ClothesBlue;
decorate *pred = new PantRed;
decorate *pblue = new PantBlue;
cred->set(p);
pblue->set(p);
system("pause");
return 0;
}
总结
装饰模式有效地把类的核心职责和装饰功能区分开,可以去除相关类中的重复装饰逻辑