C++与设计模式(11)——装饰模式

装饰模式动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。
装饰模式注重功能的拓展,增加了类的组合,减少了类之间的继承,而多个装饰类进行排练组合,可以创造出不同行为的组合。

//穿衣服的人
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值