装饰器模式(c++)
#include<iostream> #include<string> #include<list> 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 = 10; mMp = 10; mAt = 10; mDf = 10; } virtual void ShowStatus() { cout << "血量:" << mHp << endl; cout << "魔法:" << mMp << endl; cout << "攻击:" << mAt << endl; cout << "防御:" << mDf << endl; } }; //英雄穿上某个装饰物,那么他还是个英雄 class AbstractEquipment :public AbstractHero { public: AbstractEquipment(AbstractHero* hero) { pHero = hero; } virtual void ShowStatus(){} public: AbstractHero* pHero; }; //狂徒 class KuangtuEquipment :public AbstractEquipment { public: KuangtuEquipment(AbstractHero* hero):AbstractEquipment(hero){} //增加额外功能 void AddKuangtu() { cout << "英雄穿上狂徒之后..." << endl; mHp = pHero->mHp; mMp = pHero->mMp; mAt = pHero->mAt; mDf = pHero->mDf+30; delete pHero; } virtual void ShowStatus() { AddKuangtu(); cout << "血量:" << mHp << endl; cout << "魔法:" << mMp << endl; cout << "攻击:" << mAt << endl; cout << "防御:" << mDf << endl; } }; void test() { AbstractHero* hero = new HeroA; hero->ShowStatus(); cout << "-------------------" << endl; //给裸奔的英雄穿上衣服 hero = new KuangtuEquipment(hero); hero->ShowStatus(); delete hero; } int main() { test(); cin.get(); return 0; }