使用面向对象的抽象,Observer模式使得我们可以独立地改变目标与观察者,从而使二者之间的依赖关系达致松耦合。
目标发送通知时,无需指定观察者,通知(可以携带通知信息作为参数)会自动传播
观察者自己决定是否需要订阅通知,目标对象对此一无所知
#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 停止攻击 等待状态.." << 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 aadHero(AbstractHero* hero) = 0;
virtual void delHero(AbstractHero* hero) = 0;
virtual void notify() = 0;
protected:
list<AbstractHero*> pHeroList_;
};
class BossA :public AbstractBoss
{
virtual void aadHero(AbstractHero* hero){
pHeroList_.push_back(hero);
}
virtual void delHero(AbstractHero* hero) {
pHeroList_.remove(hero);
}
virtual void notify() {
for (AbstractHero* hero : pHeroList_)
{
hero->update();
}
}
};
void test1() {
AbstractHero* heroA = new HeroA;
AbstractHero* heroB = new HeroB;
AbstractHero* heroC = new HeroC;
AbstractHero* heroD = new HeroD;
AbstractBoss* boss = new BossA;
boss->aadHero(heroA);
boss->aadHero(heroB);
boss->aadHero(heroC);
boss->aadHero(heroD);
cout << "herro C 阵亡" << endl;
boss->delHero(heroC);
cout << "boss 阵亡,通知其他英雄停止攻击" << endl;
boss->notify();
}
int main()
{
test1();
}