Java Reference
In-Depth Information
Note The Observer design pattern is not normally used for one part of a GUI to receive notifications of
changes to another part of the GUI. It is more common to have an Observable model in an MVC pattern
with one or more Observer views. Or you might have an Observable server that notifies all the Observer
clients whenever something changes on the server.
Normally you would have the class you wish to observe extend the Observable class, but
our ConfigOptions panel already extends JPanel , so we cannot do this. Instead, we have cre-
ated an inner class that extends Observable , and provided a convenient getObservable
method that the client and server applications can use in order to register themselves as
observers.
When using Java's inbuilt implementations of the observer pattern, you can specify an
object that should be passed to the observers. We have created a value object class that can be
used to pass the field that was changed along with the field contents. This class is presented in
Listing 8-29. For more information on the Value Object design pattern, refer to Chapter 5.
Listing 8-29. The OptionUpdate Value Object
package sampleproject.gui;
public class OptionUpdate {
public enum Updates {
NETWORK_CHOICE_MADE,
DB_LOCATION_CHANGED,
PORT_CHANGED;
}
private Updates updateType = null;
private Object payload = null;
public OptionUpdate(Updates updateType, Object payload) {
this.updateType = updateType;
this.payload = payload;
}
public Updates getUpdateType() {
return this.updateType;
}
public Object getPayload() {
return payload;
}
}
When the user changes something in the common dialog box (which is the class that
might have some Observer s), one of the event handlers will be called. If this is an event we
Search WWH ::




Custom Search