代码如下:
#include <iostream>
#include <list>
using namespace std;class AbstractHero
{
public:virtual void update() = 0;
};class HeroA :public AbstractHero
{
public:HeroA(){cout << "英雄A正在打BOSS" << endl;}virtual void update(){cout << "英雄A停止打BOSS,处于待机状态" << endl;}
};class HeroB :public AbstractHero
{
public:HeroB(){cout << "英雄B正在打BOSS" << endl;}virtual void update(){cout << "英雄B停止打BOSS,处于待机状态" << endl;}
};class HeroC :public AbstractHero
{
public:HeroC(){cout << "英雄C正在打BOSS" << endl;}virtual void update(){cout << "英雄C停止打BOSS,处于待机状态" << endl;}
};class HeroD :public AbstractHero
{
public:HeroD(){cout << "英雄D正在打BOSS" << endl;}virtual void update(){cout << "英雄D停止打BOSS,处于待机状态" << endl;}
};class HeroE :public AbstractHero
{
public:HeroE(){cout << "英雄E正在打BOSS" << endl;}virtual void update(){cout << "英雄E停止打BOSS,处于待机状态" << endl;}
};class AbstractBoss
{
public:virtual void addHero(AbstractHero *hero) = 0;virtual void deleteHero(AbstractHero *hero) = 0;virtual void notify() = 0;
};class BossA :public AbstractBoss
{
public:virtual void addHero(AbstractHero *hero){heroList.push_back(hero);}virtual void deleteHero(AbstractHero *hero){heroList.remove(hero);}virtual void notify(){for (list<AbstractHero *>::iterator it = heroList.begin(); it != heroList.end(); it++){(*it)->update();}}public:list<AbstractHero *> heroList;
};void test01()
{AbstractHero *heroA = new HeroA;AbstractHero *heroB = new HeroB;AbstractHero *heroC = new HeroC;AbstractHero *heroD = new HeroD;AbstractHero *heroE = new HeroE;AbstractBoss *bossA = new BossA;bossA->addHero(heroA);bossA->addHero(heroB);bossA->addHero(heroC);bossA->addHero(heroD);bossA->addHero(heroE);cout << "heroC 阵亡" << endl;bossA->deleteHero(heroC);cout << "bossA死了,通知其他英雄停止攻击" << endl;bossA->notify();
}int main()
{test01();return 0;
}
测试结果: