观察者模式
定义
定义对象间的一种一对多(变化)的依赖关系,以便当一个对象(Subject)的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。 ——《 设计模式》 GoF
使用背景
气象站读取气象资料并发布给数据中心,数据中心经过处理,将气象信息更新到两个不同的显示终端(A 和B);
结构图
未使用设计模式前的代码
class DisplayA {
public:
void Show(float temperature);
};
class DisplayB {
public:
void Show(float temperature);
};
class WeatherData {
};
class DataCenter {
public:
float CalcTemperature() {
WeatherData * data = GetWeatherData();
// ...
float temper/* = */;
return temper;
}
private:
WeatherData * GetWeatherData(); // 不同的方式
};
int main() {
DataCenter *center = new DataCenter;
DisplayA *da = new DisplayA;
DisplayB *db = new DisplayB;
float temper = center->CalcTemperature();
da->Show(temper);
db->Show(temper);
return 0;
}
可见没有使用设计模式的时候我们每次都需要从数据中心读取数据,之后在传参到每个终端,这样编程需要在新添加终端的时候在dc->show(temper),不断这样增加下去,如果存在显示其他数据,则需要修改的地方很多很乱。
观察者模式下的代码
class IDisplay {
public:
virtual void Show(float temperature) = 0;
virtual ~IDisplay() {}
};
class DisplayA : public IDisplay {
public:
virtual void Show(float temperature);
};
class DisplayB : public IDisplay{
public:
virtual void Show(float temperature);
};
class WeatherData {
};
class DataCenter {
public:
void Attach(IDisplay * ob);
void Detach(IDisplay * ob);
void Notify() {
float temper = CalcTemperature();
for (auto iter = obs.begin(); iter != obs.end(); iter++) {
(*iter)->Show(temper);
}
}
private:
virtual WeatherData * GetWeatherData();
virtual float CalcTemperature() {
WeatherData * data = GetWeatherData();
// ...
float temper/* = */;
return temper;
}
std::vector<IDisplay*> obs;
};
int main() {
DataCenter *center = new DataCenter;
IDisplay *da = new DisplayA();
IDisplay *db = new DisplayB();
center->Attach(da);
center->Attach(db);
center->Notify();
//-----
center->Detach(db);
center->Notify();
return 0;
}
观察者模式使得我们可以独立地改变目标与观察者,从而使二者之间的关系松耦合;观察者自己决定是否订阅通知,目标对象并不关注谁订阅了;观察者不要依赖通知顺序,目标对象也不知道通知顺序;每次添加只要在数据初始化的地方把把对象Attach到数据中心就行了。
总结
观察者模式也可以叫做发布订阅模式,用于服务器向客户端发送数据,用于分布式处理中