观察者模式:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都要得到通知并自动更新。
在观察者模式中有两种角色:观察者和监听者
观察者:通知对该事件感兴趣的监听者
监听者:处理事件
事件对于监听者可以是1对1,也可以是1对多的关系
举个例子:教室里有几个学生,趁着老师没在,各自做着与学习无关的事,小李在玩手机,小王在看小说,小刘在打游戏,他们让小胡帮忙看着老师,如果老师来了,通知他们,那么,此时,小李、小王、小刘就是监听者,小胡就是观察者,当老师来时,小胡作为观察者,会将老师来了这个事件通知三位监听者,监听者收到通知后会处理事件,也就是停下他们这在做的事并假装自己在学习,这里事件对于监听者的关系就是一对多的关系。
#include<iostream>
#include<string>
#include<map>
#include<vector>
using namespace std;
class Listener
{
public:
Listener(string name):mname(name){}
virtual void handleMessage(int message)const=0;
protected:
string mname;
};
class Listener1:public Listener
{
public:
Listener1(string name):Listener(name){}
virtual void handleMessage(int message)const
{
switch(message)
{
case 1:
cout<<mname<<"has been soved1 message!"<<endl;
case 2:
cout<<mname<<"has been soved2 message!"<<endl;
default:
cout<<mname<<"no interested this message!"<<endl;
break;
}
}
};
class Listener2:public Listener
{
public:
Listener2(string name):Listener(name){}
virtual void handleMessage(int message)const
{
switch(message)
{
case 2:
cout<<mname<<"has been soved2 message!"<<endl;
case 3:
cout<<mname<<"has been soved3 message!"<<endl;
default:
cout<<mname<<"no interested this message!"<<endl;
break;
}
}
};
class Listener3:public Listener
{
public:
Listener3(string name):Listener(name){}
virtual void handleMessage(int message)const
{
switch(message)
{
case 1:
cout<<mname<<"has been soved1 message!"<<endl;
case 3:
cout<<mname<<"has been soved3 message!"<<endl;
default:
cout << mname << " no interested this message!" <<endl;
break;
}
}
};
class Observe
{
public:
typedef map<int,vector<const Listener*>> Mty;
typedef vector<const Listener*> Vty;
void notify(int message)
{
Mty::iterator fit=mymap.find(message);
if(fit!=mymap.end())
{
Vty::iterator it=fit->second.begin();
while(it!=fit->second.end())
{
(*it)->handleMessage(message);
it++;
}
}
}
void registerMessage(int message,const Listener* pls)
{
Mty::iterator fit=mymap.find(message);
if(fit!=mymap.end())
{
fit->second.push_back(pls);
}
else
{
Vty vec;
vec.push_back(pls);
mymap[message]=vec;
}
}
private:
map<int,vector<const Listener*>> mymap;
};
int main()
{
Listener1 l1("listener1");
Listener2 l2("listener2");
Listener3 l3("listener3");
Observe ob;
ob.registerMessage(1, &l1);
ob.registerMessage(2, &l1);
ob.registerMessage(2, &l2);
ob.registerMessage(3, &l2);
ob.registerMessage(1, &l3);
ob.registerMessage(3, &l3);
ob.notify(3);
return 0;
}