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

我想问当我需要实现这样的目标时应该如何正确实现观察者模式:

I would like to ask how I should correctly implement observer pattern when I need to achieve something like this:

WeatherStation[temperature, humidity ...]

,我需要能够观察"每个属性独立.因此,当温度变化时,只会通知温度观测者,而当湿度变化时,只会通知湿度用户.

and I need to be able to "observe" each attribute independently. So when temperature changes only temperature observers will be notified, when humidity changes only humidity subscribers will be notified.

我的想法是,我将创建一些类,例如ObservableTemperature和接口TemperatureObserver,但是通过这种方式,我将不得不创建两个"classes"类.每个属性.

My idea was that I would create some classes like ObservableTemperature and interface TemperatureObserver but I this way I would have to create two "classes" for each attribute.

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

Second option is to create only two interfaces for each attribute (something like TemperatureSource, TemperatureObserver ...) and then implement the xxxSource interface in WeatherStation class but this way it is not reusable and I would need to have in WeatherStation class a lot of arrays (same number as "observable" attributes) keeping track of observers.

还有更好的选择吗?

同样,也可能发生类似Display类的事件,该事件将订阅多个属性(不是全部),并且仍然需要区分其中哪一个已更新.

EDITED: Also it can also happen that I would have something like Display class which would subscribe to multiple attributes(not all) and still need to distinguish which one of them was updated.



 1 条回答