设计模式-装饰模式

shienh 2020年01月22日 150次浏览

装饰(Decorator)模式的定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。

装饰(Decorator)模式的主要优点有:

采用装饰模式扩展对象的功能比采用继承方式更加灵活。
可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。

其主要缺点是:装饰模式增加了许多子类,如果过度使用会使程序变得很复杂。

#include <iostream>
using namespace std;

class AbstractHero{
public:
    virtual void ShowStatus()=0;
public:
    int mHp;//血量
    int mMp;//魔法
    int mAt;//攻击
    int mDf;//防御
};

class HeroA:public AbstractHero{
public:
    HeroA(){
         mHp=0;
         mMp=0;
         mAt=0;
         mDf=0;
    }
    virtual void ShowStatus(){
        cout<<"mHp:"<<mHp<<endl;
        cout<<"mMp:"<<mMp<<endl;
        cout<<"mAt:"<<mAt<<endl;
        cout<<"mDf:"<<mDf<<endl;
    }
};

//英雄穿上装饰物之后,还是英雄
class AbstractEquipment:public AbstractHero{
public:
    AbstractEquipment(AbstractHero* Hero){
        this->pHero = Hero;
    }
    virtual void ShowStatus(){}

public:
    AbstractHero* pHero;
};


//狂徒防御装备
class KuangtuEquipment:public AbstractEquipment{
public:
    KuangtuEquipment(AbstractHero* hero):AbstractEquipment(hero){}
    void AddKuangtu(){
        this->mHp = this->pHero->mHp;
        this->mMp = this->pHero->mMp;
        this->mAt = this->pHero->mAt;
        this->mDf = this->pHero->mDf+30;
        delete this->pHero;

    }
    virtual void ShowStatus(){
        AddKuangtu();
        cout<<"mHp:"<<mHp<<endl;
        cout<<"mMp:"<<mMp<<endl;
        cout<<"mAt:"<<mAt<<endl;
        cout<<"mDf:"<<mDf<<endl;
    }
};


//血饮狂刀
class WuqiEquipment:public AbstractEquipment{
public:
    WuqiEquipment(AbstractHero* hero):AbstractEquipment(hero){}
    void AddXueyin(){
        this->mHp = this->pHero->mHp;
        this->mMp = this->pHero->mMp;
        this->mAt = this->pHero->mAt+50;
        this->mDf = this->pHero->mDf;
        delete this->pHero;

    }
    virtual void ShowStatus(){
        AddXueyin();
        cout<<"mHp:"<<mHp<<endl;
        cout<<"mMp:"<<mMp<<endl;
        cout<<"mAt:"<<mAt<<endl;
        cout<<"mDf:"<<mDf<<endl;
    }
};



int main(int argc, char *argv[])
{
    AbstractHero* hero = new HeroA;
    hero->ShowStatus();
    cout<<endl;

    hero = new WuqiEquipment(hero);
    hero->ShowStatus();

    cout<<endl;

    hero = new KuangtuEquipment(hero);
    hero->ShowStatus();

    delete  hero;
    return 0;
}