觀察者模式:定義了一種一對多的依賴關系,讓多個觀察者對象同時監(jiān)聽某一主題對象,在它的狀態(tài)發(fā)生變化時,會通知所有的觀察者.
#include<list>
#include<iostream>
using namespace std;
class TecherListenner;
class TecherListenner;
class INotifier{
public:
virtual void addListenner(TecherListenner* listenner)=0;
virtual void removeListenner(TecherListenner* listenner) = 0;
virtual void notify() = 0;
};
//然后班長作為一個具體的通知者:
class TecherNotifier:public INotifier{
public:
virtual ~TecherNotifier(){}
virtual void addListenner(TecherListenner* listenner){
m_listenners.push_back(listenner);
}
virtual void removeListenner(TecherListenner* listenner)
{
m_listenners.remove(listenner);
delete listenner;
}
virtual void notify()
{
for( auto & i : m_listenners)
{
i->onTecherComming();
}
}
private:
std::list<TecherListenner*> m_listenners;
};
// 定義一個監(jiān)聽者的接口,想要監(jiān)聽老師來了這個消息的同學必須要實現這個接口:
class TecherListenner{
virtual void onTecherComming()=0;
};
class XiaoZhang : public TecherListenner{
public:
virtual~XiaoZhang(){}
virtual void onTecherComming()
{
stopCopyWork();
}
void stopCopyWork()
{
std::cout<<"老師來了,停止抄作業(yè)家浇!"<<endl;
}
};
class XiaoLi : public TecherListenner{
public:
virtual~XiaoLi(){}
virtual void onTecherComming()
{
stopPlayGame();
}
void stopPlayGame()
{
cout<<"老師來了初嘹,停止玩游戲機蜒蕾!"<<endl;
}
};