观察者模式:独立观察属性

Observer pattern: observe attributes independently

请问在需要实现这样的功能时,应该如何正确实现观察者模式:

WeatherStation[temperature, humidity ...]

而且我需要能够独立地“观察”每个属性。因此,当温度发生变化时,只会通知温度观察者,当湿度发生变化时,只会通知湿度订阅者。

我的想法是我会创建一些像 ObservableTemperature 和接口 TemperatureObserver 这样的 classes 但我这样我就必须为每个属性创建两个“classes”。

第二个选项是只为每个属性创建两个接口(类似于 TemperatureSource、TemperatureObserver ...),然后在 WeatherStation class 中实现 xxxSource 接口,但这种方式不可重用,我需要在 WeatherStation class 中有很多数组(与“可观察”属性的数量相同)跟踪观察者。

有没有更好的选择?

已编辑: 也有可能我会有像 Display class 这样的东西,它会订阅多个属性(不是全部),但仍然需要区分更新的属性。

temperaturehumidity等组合成classWeatherStation定义了一个领域概念。就观察者模式而言,这是一个主题。另一方面,发送包含单个值的通知会将 WeatherStation 划分为多个领域概念和多个主题。显然这两个设计决策之间存在冲突。

GoF 模式是根据对象(而不是字段)作为主题来定义的。但请注意,这并不限制一个主题在不同时间通知不同的观察者。本书的相关部分从第 298 页开始。

Specifying modifications of interest explicitly. You can improve update efficiency by extending the subject's registration interface to allow registering observers only for specific events of interest. When such an event occurs, the subject informs only those observers that have registered interest in that event. One way to support this uses the notion of aspects for Subject objects. To register interest in particular events, observers are attached to their subjects using

void Subject::Attach(Observer*, Aspects interest);

where interest specifies the event of interest. At notification time, the subject supplies the changed aspect to its observers as a parameter to the Update operation. For example:

void Observer::Update(Subject*, Aspect& interest);

这种方法使不同的观察者可以注册一个 Subject 的不同通知。请注意,无论观察者注册了哪个方面,它都会在通知消息中收到相同的 Subject。由观察者从 Subject.

中读取必要的字段