Observer – specifying modifications of interest explicitly – JAVA implementation

Tags: , ,



I asked here how I should handle the situation when I need to inform observers only when specific attribute of object changes.

I received very nice reply with reference to GoF where is written:

Blockquote 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);

Blockquote 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);

This makes sense and I would like to ask how to correctly implement this in Java. I have few ideas but I am not sure if there isn’t something better.

Let’s imagine I have subject class WeatherStation[temperature, humidity, windSpeed ...] and I have observer class LimitedDisplay[show (shows only temperature and humidity) and for some reason I need that the display should be able to differentiate when only temperature was changed and when only humidity was changed.

I was thinking that I could create some enum WeatherStationInterest[TEMPERATURE, HUMIDITY WIND_SPEED...] and then have the subject interface like this:

public interface WeatherStationSubject{
    registerObserver(WeatherStationObserver observer, WeatherStationInterest... interests);
    .
    .
    .
}

Could someone confirm me that this is correct way how to do it or advice me better solution.

Answer

Another option is to have a set of interfaces:

interface TemperatureListener {
    onTemperatureChange(double newTemperature);
}
interface HumidityListener {
    onHumidityChange(double newHumidity);
}
...

Then the registration method looks like:

void registerListener(Object listener)

And you’d implement a listener:

class MyListener implements TemperatureListener, HumidityListener {
...
}

Not necessarily better, but makes it simple to see what has actually changed, if that’s important.



Source: stackoverflow