定义对象间一对多的依赖关系,使得每一个对象状态改变,则所有依赖他的对象都会得到通知
观察者模式 : 秘书站在门口,看见老板来了,发出信号,老板来了,,然后 员工通过观察秘书信号
停止打游戏
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Secretary;
//观察者
class PlayGamerPeople
{
public:
PlayGamerPeople(Secretary *s)
{
this->_secretary = s;
}
void update(string action)
{
//this->_secretary->speak();
cout << " " << action << " PlayGamerPeople停止打游戏"<<endl;
}
private:
Secretary *_secretary;
};
//发信号者
class Secretary
{
public:
Secretary()
{
_list.clear();
}
void notipy(string notipy)
{
auto it = _list.begin();
for (it; it != _list.end(); it++)
{
(*it)->update(notipy);
}
}
void speak()
{
cout << "我是秘书我说:";
}
void setPlayGamerPeople(PlayGamerPeople* s)
{
_list.push_back(s);
}
private:
list<PlayGamerPeople*> _list;
};
int main()
{
PlayGamerPeople *pl1 = nullptr;
PlayGamerPeople *pl2 = nullptr;
Secretary *se = nullptr;
se = new Secretary;
pl1 = new PlayGamerPeople(se);
pl2 = new PlayGamerPeople(se);
se->setPlayGamerPeople(pl1);
se->setPlayGamerPeople(pl2);
se->notipy("老板来了");
return 0;
}