装饰模式:
通过AbstractEquipment装饰AbstractHero,使其heroA增加了一个穿装备的功能。
代码如下:
#include <iostream>
using namespace std;class AbstractHero
{public:virtual void showStatus() = 0;int hp;int mp;int at;int df;
};class HeroA :public AbstractHero
{
public:HeroA() {hp = 0;mp = 0;at = 0;df = 0;}virtual void showStatus(){cout << "血量 = " << hp << endl;cout << "魔法 = " << mp << endl;cout << "攻击 = " << at << endl;cout << "防御 = " << df << endl;}
};class AbstractEquipment :public AbstractHero
{
public:AbstractEquipment(AbstractHero *hero){this->hero = hero;}virtual void showStatus(){}AbstractHero *hero;
};class Kuangtu :public AbstractEquipment
{
public:Kuangtu(AbstractHero *hero):AbstractEquipment(hero){}void addKuangtu(){cout << "英雄穿上狂徒之后" << endl;this->hp = this->hero->hp;this->mp = this->hero->mp;this->at = this->hero->at;this->df = this->hero->df+30;delete this->hero;}virtual void showStatus(){addKuangtu();cout << "血量 = " << hp << endl;cout << "魔法 = " << mp << endl;cout << "攻击 = " << at << endl;cout << "防御 = " << df << endl;}
};class WujinzhiKinfe :public AbstractEquipment
{
public:WujinzhiKinfe(AbstractHero *hero):AbstractEquipment(hero){}void addWujinzhiKinfe(){cout << "英雄拿上无尽之刃之后" << endl;this->hp = this->hero->hp;this->mp = this->hero->mp;this->at = this->hero->at+30;this->df = this->hero->df ;delete this->hero;}virtual void showStatus() {addWujinzhiKinfe();cout << "血量 = " << hp << endl;cout << "魔法 = " << mp << endl;cout << "攻击 = " << at << endl;cout << "防御 = " << df << endl;}
};void test01()
{AbstractHero *hero = new HeroA;hero->showStatus();cout << "---------------------" << endl;hero = new Kuangtu(hero);hero->showStatus();hero = new WujinzhiKinfe(hero);hero->showStatus();
}int main()
{test01();return 0;
}
测试结果: