Implementing the observer pattern in Java
Basic means
To implement the observer pattern in Java, we can use some basic, but simple
means, which comes as a base class java.util.Observable and
an interface java.util.Observer. To demonstrate their use, we implement a special
version of an Integer (becoming our observable), which is capable
of notifying one or more observers about changes in its value.
The example code can be downloaded here.
The observable
The observable extends the base class java.util.Observable and gets the methods
setChanged() and notifyObservers(id) for free, which will
be used as follows:
import java.util.Observable;
class ObInt extends Observable {
private int m_Var;
public void setInt(int pVar){
m_Var = pVar;
System.out.println("observable has changed, notifying observers ...");
setChanged();
notifyObservers("ObInt");
}
public int getInt(){
return m_Var;
}
}
|
Each time the value of our observable integer object is changed by the
setInt() method, we mark the object as dirty by calling the
setChanged() method and notify then our possible observers
by a call to notifyObservers(id). The specified id, in our
example the String ObInt will be passed to all observers as
additional information, together with the observable itself. See description
of the observer below.
The observer
The observer implements the interface java.util.Observer,
which enforces the coding of a method update(observable, id).
This method is called every time a dirty observable has called its
notifyObserver method. The specified id is exactly the same String
which was passed to the notifyObserver method. The observable
itself can be evaluated in the update method to retrieve the
changed information.
To get things working, we must remember to register the observing object
as an observer on the observable. This is done by calling the addObserver(listener)
method of the observer which adds the listener to the listener list of the
observable.
import java.util.Observer;
public class Observ implements Observer {
ObInt o;
private Observ() {
try {
o = new ObInt();
o.addObserver(this);
System.out.println("There are now " + o.countObservers() + " observers");
Thread.sleep(1000);
System.out.print("setting value ... ");
o.setInt(15);
System.out.println("done");
Thread.sleep(100);
Thread.sleep(100);
Thread.sleep(1000);
} catch(Exception e) {
System.out.println(e);
};
}
public static void main(String args[]){
new Observ();
}
public void update(Observable pO, Object pArg){
System.out.println("Value (id=" + (String)pArg +
") is now " + ((ObInt)pO).getInt());
}
}
|
back to toolbox page
|