UPDATE Added the full code to make it easier to understand.
I am trying to understand how to implement push vs pull notifications using Java built-in Observer.
the Observable
class has 2 methods notifyObservers()
and notifyObservers(Object arg)
according to the docs:
Each observer has its update
method called with two arguments: this observable object and the arg
argument.
here is my Observer class
public class CurrentConditionsDisplay implements Observer, DisplayElement {
private float temperature;
private float humidity;
private Observable observable;
public CurrentConditionsDisplay(Observable observable) {
this.observable = observable;
observable.addObserver(this);
}
@Override
public void display() {
System.out.println("Current conditions: " + temperature + "F degrees and "
+ humidity + "% humidity");
}
@Override
public void update(Observable o, Object arg) {
/*
if (o instanceof WeatherData) {
WeatherData weatherData = (WeatherData) o;
this.temperature = weatherData.getTemperature();
this.humidity = weatherData.getHumidity();
}*/
if (arg instanceof WeatherData) {
WeatherData weatherData = (WeatherData) arg;
this.temperature = weatherData.getTemperature();
this.humidity = weatherData.getHumidity();
}
display();
}
and in my observable class
public class WeatherData extends Observable {
private float temperature;
private float humidity;
private float pressure;
private void measurementsChanged() {
setChanged();
//notifyObservers();
notifyObservers(this);
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
I've tried both methods, and both objects can be cast down to WeatherData(the Observer) and then get the data from them.
using both methods seem like push notification-type for me, so what is the difference? and how can I implement pull notification-type using it?