观察者模式(c++)

#include<iostream>
#include<string>
#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停止撸,待机状态..." << endl;
	}
};
class HeroB :public AbstractHero {
public:
	HeroB() {
		cout << "英雄B正在撸Boss" << endl;
	}
	virtual void Update() {
		cout << "英雄B停止撸,待机状态" << endl;
	}
};
class HeroC :public AbstractHero {
public:
	HeroC() {
		cout << "英雄C正在撸Boss" << endl;
	}
	virtual void Update() {
		cout << "英雄C停止撸,待机状态" << endl;
	}
};
class HeroD :public AbstractHero {
public:
	HeroD() {
		cout << "英雄D正在撸Boss" << endl;
	}
	virtual void Update() {
		cout << "英雄D停止撸,待机状态" << endl;
	}
};

//观察目标抽象
class AbstractBoss{
public:
	//添加观察者
	virtual void addHero(AbstractHero* hero) = 0;
	//删除观察者
	virtual void deleteHero(AbstractHero* hero) = 0;
	//通知所有观察者
	virtual void notify() = 0;
};
//具体的观察者  BossA
class BossA :public AbstractBoss {
public:
	virtual void addHero(AbstractHero* hero) {
		pHeroList.push_back(hero);
	}
	virtual void deleteHero(AbstractHero* hero) {
		pHeroList.remove(hero);
	}
	virtual void notify() {
		for (list<AbstractHero*>::iterator it = pHeroList.begin(); it !=pHeroList.end(); it++)
		{
			(*it)->Update();
		}
	}


private:
	list<AbstractHero*> pHeroList;
};

void test() {
	//创建观察者
	AbstractHero* heroA = new HeroA;
	AbstractHero* heroB = new HeroB;
	AbstractHero* heroC = new HeroC;
	AbstractHero* heroD = new HeroD;

	//创建观察目标
	AbstractBoss* bossA = new BossA;
	bossA->addHero(heroA);
	bossA->addHero(heroB);
	bossA->addHero(heroC);
	bossA->addHero(heroD);

	cout << "heroC阵亡..." << endl;
	bossA->deleteHero(heroC);
	cout << "Boss死亡....通知其他英雄停止攻击,抢装备..." << endl;
	bossA->notify();

	delete heroA;
	delete heroB;
	delete heroC;
	delete heroD;
}

int main() {
	test();
	cin.get();
}

  

posted @ 2024-03-25 17:51  dmfsimle  阅读(2)  评论(0编辑  收藏  举报