首页 > 代码库 > 观察者模式
观察者模式
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
class Observer
{
public:
virtual void update() = 0;
};
typedef vector<Observer*> VEC_OBS;
class Subject
{
private:
VEC_OBS mObs;
public:
void addObserver(Observer * obs)
{
this->mObs.push_back(obs);
}
void delObserver(Observer * obs)
{
}
void notifyObserver()
{
VEC_OBS::iterator iter = mObs.begin();
for(iter=mObs.begin(); iter!= mObs.end(); iter++)
{
Observer * pObs = *iter;
pObs->update();
}
}
virtual void doSomething() = 0;
};
class ConSubject1 : public Subject
{
public:
void doSomething()
{
cout<<"被观察者事件发生"<<endl;
this->notifyObserver();
}
};
class Observer1: public Observer
{
public:
void update()
{
cout<<"观察者1收到消息"<<endl;
}
};
class Observer2: public Observer
{
public:
void update()
{
cout<<"观察者2收到消息"<<endl;
}
};
void main()
{
Subject * pSub = new ConSubject1();
pSub->addObserver(new Observer1());
pSub->addObserver(new Observer2());
pSub->doSomething();
}
观察者模式