Observer/Observable Example
Using SUN JDK Observer/Observable Pattern: Manual Drivers, Synthesized drivers, All sourcesThis is an example of implementation of an Observer/Observable pattern. This pattern is used to define a dependancy between objects that allows objects playing a role of observers to monitor a state of objects playing a role of observables. This pattern can be used when a change in one object needs to be propagated to its dependable objects. In this case, dependable objects can register to monitor the state of observable by calling observable.addObserver(observer) and cancel their registration by calling observable.deleteObserver(observer). When observable changes its state, it will notify all of the observers about it. State change of observable and notification is depicted by observable calling its method setChanged() followed by notifyObservers(). The method notifyObservers() contains code that calls update() method of each of the observers that were registered to monitor the state of observable.
The example contains implementation of Watcher and Subject playing roles of Observer and Observable. The code for Watcher and Subject is taken from SUN JDK implementation of java.util.Observer and java.util.Observable (version 1.10 of Observer and version 1.19 of Observable which were written by Chris Warth and which are both copyright by Sun Microsystems, Inc.) The ObserverDriver creates a Subject s and two Watchers w1 and w2. The state of s is constantly changed by calling s.changeState() that is implemented as a sequence of setChanged() followed by notifyObservers(). The two watchers are nondeterminitically get registered on s or cancel their registration on s.
The two properties that are desirable for the observer/observable system are:
(1) only registered observers are notified of updates, and
(2) all registered observers are notified of updates.