Java Reference
In-Depth Information
The definition of the class for observed objects could be of the form:
public class Document extends Observable {
// Details of the class definitions
}
The class Document here will inherit methods from the class Observable that operate the
communications to the Observer objects.
A class for observers could be defined as:
public class View implements Observer {
// Method for the interface
public void update(Observable theObservableObject, Object arg) {
// This method is called when the observed object changes
}
// Rest of the class definition...
}
To implement the Observer interface we need to define just one method, update() . This method is
called automatically when an associated Observable object changes. The first argument that is passed
to the update() method is a reference to the Observable object that changed and caused the
method to be called. This enables the View object to access public methods in the associated
Observable object, which would be used to access the data to be displayed, for example. The second
argument passed to update() is used to convey additional information to the Observer object.
Observable Class Methods
The Observable class maintains an internal record of all the Observer objects related to the object
to be observed. Your class, derived from Observable , will inherit the data members that deal with
this. Your class of observable objects will also inherit nine methods from the class Observable . These
are the following:
Method
Description
addObserver(Observer o)
Adds the object passed as an argument to the internal
record of observers. Only Observer objects in the
internal record will be notified when a change in the
Observable object occurs.
deleteObserver
(Observer o)
Deletes the object passed as an argument from the
internal record of observers.
deleteObservers()
Deletes all observers from the internal record of
observers.
Table continued on following page
Search WWH ::




Custom Search