观察者模式:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新
我们每天都要根据天气来做一些事情
#include "stdafx.h"
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<stack>
#include<vector>
#include<deque>
#include<list>
#include <iterator>
using namespace std;
typedef enum
{
rainy,
sunny,
foggy
} weatherStatus;
class weather;
class ob
{
public:
ob::ob();
ob:: ~ob();
virtual void ob::update()=0;
static weather* p_weather;
};
class peopleSH : public ob
{
public:
peopleSH(string name);
~peopleSH();
void update();
private:
string mName;
};
class weather
{
public :
weather();
virtual ~weather();
void attachob(ob* P_ob);
void remove(ob* P_ob);
void notify();
weatherStatus getWeatherStatus();
void setWeatherStatus(weatherStatus weather);
private:
list <ob*> mObList;
weatherStatus mWeather;
};
class weatherSH : public weather
{
public:
weatherSH();
~weatherSH();
};
weather::weather():mWeather(sunny){};
weather::~weather(){};
void weather::attachob(ob* P_ob){mObList.push_back(P_ob);};
void weather::remove(ob* P_ob) {mObList.remove(P_ob);};
void weather::notify()
{
list <ob*> ::iterator it = mObList.begin();
for(;it!= mObList.end();++it)
{
(*it)->update();
}
};
void weather::setWeatherStatus(weatherStatus weather)
{
mWeather = weather;
}
weatherStatus weather::getWeatherStatus(void)
{
return mWeather;
}
weatherSH::weatherSH(){};
weatherSH::~weatherSH(){};
ob::ob(){};
weather* ob::p_weather = new weatherSH();
ob:: ~ob()
{
if(p_weather != NULL)
{
delete p_weather;
p_weather = NULL;
}
};
peopleSH::peopleSH(string name):mName(name)
{
};
peopleSH::~peopleSH()
{
};
void peopleSH::update()
{
weatherStatus today = p_weather->getWeatherStatus();
switch(today)
{
case rainy: cout<< mName.c_str() << " : get the umbrella"<<endl; break;
case sunny: cout<< mName.c_str() << " :mood seems good"<<endl; break;
case foggy: cout<< mName.c_str() << " : it seems bad"<<endl; break;
default: cout << "weather error!"<<endl; break;
}
}
void main()
{
ob * p_ob1 = new peopleSH("banana");
ob * p_ob2 = new peopleSH("apple");
weather* p_sh =ob::p_weather;
p_sh->attachob(p_ob1);
p_sh->attachob(p_ob2);
p_sh->setWeatherStatus(rainy);
p_sh->notify();
p_sh->setWeatherStatus(foggy);
p_sh->notify();
cin.get();
}
总的来说,就是将观察者加到观察对象的成员list中,当观察对象发布消息时notify,遍历list去更新观察者的行为
这是一种很好用的模式,和函数指针的思想类似,关注这个消息的对象去注册它,发布命令时调用