被观察者维护一个队列,将观察者放入队列。有消息就通知观察者。下面展示一些 示例代码片
。
/*
江湖中有多个帮派,还有一名无人不知,无事不晓的百晓生。当江湖中
发生武林打斗事件,百晓生作为天生的大嘴巴会广播武林消息,每个帮派的门
第对于事件的处理方式均不同,同帮派被欺负,要报仇,同帮派欺负别人,叫
好。
*/
#include <iostream>
#include <string>
#include <list>
#include <memory>
using namespace std;
//帮派的抽象接口
class gangListenner
{
public:
//
virtual void active() = 0;
};
//百晓生抽象接口
class INotifier
{
public:
virtual void addListenner(shared_ptr<gangListenner> listenner) = 0;
virtual void removeListenner(shared_ptr<gangListenner> listenner) = 0;
virtual void notify() = 0;
};
class peopleINotifier : public INotifier
{
public:
virtual void addListenner(shared_ptr<gangListenner> listenner) override
{
m_list.push_back(listenner);
}
virtual void removeListenner(shared_ptr<gangListenner> listenner) override
{
m_list.remove(listenner);
}
virtual void notify() override
{
for (auto item : m_list)
{
item->active();
}
}
private:
list<shared_ptr<gangListenner>> m_list;
};
class wudang : public gangListenner
{
public:
void active() override
{
cout << "武当派知道盟友华山派被欺负了,要替他们报仇" << endl;
}
};
class huashan : public gangListenner
{
public:
void active() override
{
cout << "华山派推选出新掌门,普天同庆" << endl;
}
};
class songshan : public gangListenner
{
public:
void active() override
{
cout << "嵩山派掌门和华山掌门一个月前争夺五岳门主职位,嵩山派掌门获胜" << endl;
}
};
int main()
{
shared_ptr<peopleINotifier> baixiao = make_shared<peopleINotifier>();
shared_ptr<gangListenner> p1 = make_shared<wudang>();
shared_ptr<gangListenner> p2 = make_shared<huashan>();
shared_ptr<gangListenner> p3 = make_shared<songshan>();
baixiao->addListenner(p3);
baixiao->addListenner(p1);
baixiao->addListenner(p2);
baixiao->notify();
return 0;
}