【c++设计模式】装饰模式

结构型模式

9)装饰模式

本文参考

https://www.jianshu.com/p/d1e4e162b5e3

装饰模式可以说是非常巧妙的一个模式了。
当想要动态得给一个对象增加功能,并且实现各种功能自由组合。如果纯粹用继承的方法的话,会产生数量多到爆炸的子类。这时装饰模式就派上用场了。
例如游戏中的人物的外形,可以给人物穿上帽子,穿上衣服裤子等装饰,或者都穿上。

装饰模式包含角色:
第一种,人物类,抽象类。
第二种,装饰器类,继承自人物类。

优点在于可以自由组合各种功能。相比于直接继承,更具有灵活性,且代码量小很多。
缺点在于由于每一步产生的对象名字都一样,不好debug。

//人物基类
class Man{
public:
    virtual void show(){
        cout<<"A man"<<endl;
    }
};
//装饰类
class ManWithCloth : public Man{
public:
    ManWithCloth(Man* m):p_man(m){}
    void show(){
        p_man->show();
        cout<<"A man with cloth"<<endl;
    }
private:
    Man* p_man;
};

//装饰类
class ManWithHat:public Man{
public:
    ManWithHat(Man* m):p_man(m){}
    void show(){
        p_man->show();
        cout<<"A man with hat"<<endl;
    }
private:
    Man* p_man;
};

int main(){
    Man* man = new Man();
    man->show();
    
    cout<<"===="<<endl;
    man = new ManWithCloth(man);
    man->show();
    
    cout<<"===="<<endl;
    man = new ManWithHat(man);
    man->show();
}

最后输出为:

原文地址:https://www.cnblogs.com/corineru/p/12019497.html