Observers and Observables
The java.util.Observer
interface and java.util.Observable
class are relatively small utilities, but they provide a glimpse of a
fundamental design pattern in Java. Observers and observables are part of
the MVC (Model-View-Controller) framework. It is an abstraction that lets
a number of client objects (the observers) be
notified whenever a certain object or resource (the
observable) changes in some way. We will see this
pattern used extensively in Java’s event mechanism, which is covered in
Chapters 16 through 19. Although
these classes are not often used directly, it’s worth looking at them in
order to understand the pattern.
The Observable object has a
method that an Observer calls to
register its interest. When a change happens, the Observable sends a notification by calling a
method in each of the Observers. The
observers implement the Observer
interface, which specifies that notification causes an Observer object’s update() method to be called.
In the following example, we create a MessageBoard object that holds a String message. MessageBoard extends Observable, from which it inherits the mechanism
for registering observers (addObserver()) and notifying observers (notifyObservers()). To observe the MessageBoard, we have Student objects that implement the Observer interface so that they can be notified
when the message changes:
//file: MessageBoard.javaimportjava.util.*;publicclassMessageBoardextendsObservable{privateStringmessage;public ...