设为首页 加入收藏

TOP

C++与设计模式(11)装饰模式
2016-12-06 20:24:43 】 浏览:273
Tags:设计模式 装饰 模式

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

//穿衣服的人
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;
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++版本归并排序 下一篇C++:深入剖析虚拟继承与虚基类表..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目