Java Reference
In-Depth Information
Defining Classes of Observable Objects
You use the
java.util.Observable
class in the definition of a class of objects that may be observed. You
simply derive the class for objects to be monitored —
Document
, say — from the
Observable
class.
Any class that may need to be notified when a
Document
object changes must implement the
Observer
interface. This doesn't in itself cause the
Observer
objects to be notified when a change in an observed
object occurs; it just establishes the potential for this to happen. You need to do something else to link the
observers to the observable, which I come to in a moment.
The definition of the class for observed objects could be of the form:
public class Document extends Observable {
// Details of the class definitions...
}
The
Document
class inherits methods that operate the communications to the
Observer
objects from the
Observable
class.
A class for observers could be defined as the following:
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, you need to define just one method,
update()
. This method is
called 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 en-
ables the
View
object to access public methods in the associated
Observable
object that would be used to
access the data to be displayed. The second argument to
update()
conveys 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
, inherits the data members that deal with this. Your class of
observable objects also inherits nine methods from the
Observable
class:
•
void addObserver(Observer o)
: Adds the object you pass as the argument to the internal record
of observers. Only
Observer
objects in the internal record are notified when a change in the
Ob-
servable
object occurs.
•
void deleteObserver(Observer o)
: Deletes the object you pass as the argument from the in-
ternal record of observers.
•
void deleteObservers()
: Deletes all observers from the internal record of observers.
•
void notifyObservers(Object arg)
: Calls the
update()
method for all of the
Observer
ob-
jects in the internal record if the current object has been set as changed. The current object is set