观察者模式:对象之间的一对多关系,当主题变化时,依赖它的对象都会收到通知并自动更新。
C++示例代码如下:
/*
* CONTENTS: DESIGN PATTERN, OBSERVER PATTERN
* AUTHOR: YAO H. WANG
* TIME: 2013-10-18 22:47:48
* EDITION: 1
*
* ALL RIGHTS RESERVED!
*/
#include <list>
#include <iostream>
using namespace std;
class DisplayElement
{
virtual void display() = 0;
};
//观察者
class Observer
{
public:
virtual void update(float temperature, float humility, float pressure) = 0;
};
//主题
class Subject
{
public:
virtual void registerObserver(Observer *ob) = 0;
virtual void removeObserver(Observer *ob) = 0;
virtual void notifyObservers() = 0;
};
class CurrentConditionsDisplay: public Observer, public DisplayElement
{
private:
Subject *su;
float temperature, humility;
public:
CurrentConditionsDisplay(Subject *su)
{
this->su = su;
su->registerObserver(this);
}
void update(float temperature, float humility, float pressure)
{
this->temperature = temperature;
this->humility = humility;
display();
}
void display()
{
cout << "Current Conditions: " << temperature <<
"F degree and " << humility << "% humility" << endl;
}
};
class WeatherData: public Subject
{
private:
list<Observer*> lo;
float temperature, humility, pressure;
public:
WeatherData()
{
//Java中此处需要生成ArrayList对象
}
void registerObserver(Observer *ob)
{
lo.push_back(ob);
}
void removeObserver(Observer *ob)
{
lo.remove(ob);
}
typedef list<Observer*>::const_iterator locit;
void notifyObservers()
{
for(locit l=lo.begin(); l!=lo.end(); ++l)
(*l)->update(temperature, humility, pressure);
}
void measurementsChanged(float temperature, float humility, float pressure)
{
this->temperature = temperature;
this->humility = humility;
this->pressure = pressure;
notifyObservers();
}
};
//测试
void main()
{
WeatherData *wd = new WeatherData();
Observer *ob = new CurrentConditionsDisplay(wd);
wd->measurementsChanged(80, 65, 30.4f);
delete wd;
delete ob;
}