装饰模式动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。
装饰模式注重功能的拓展,增加了类的组合,减少了类之间的继承,而多个装饰类进行排练组合,可以创造出不同行为的组合。
//穿衣服的人
class People
{
public:
virtual void showClothes() = 0;
};
class Someone : public People
{
public:
void showClothes(){cout << "clothe ";}
};
//衣服
class Clothe : public People
{
public:
Clothe(People *people): m_people(people) {}
virtual void showClothes(){m_people->showClothes();}
private:
People *m_people;//装饰对象
};
class Shirt : public Clothe
{
public:
Shirt(People *people): Clothe(people) {}
void showClothes(){Clothe::showClothes();cout << "shirt ";}
};
class Overcoat : public Clothe
{
public:
Overcoat(People *people): Clothe(people) {}
void showClothes(){Clothe::showClothes();cout << "overcoat ";}
};
int main()
{
People *people = new Someone;
People *shirt = new Shirt(people);
People *overcoat = new Overcoat(shirt);
overcoat->showClothes();
delete people;
delete shirt;
delete overcoat;
return 0;
}