Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 18: java.util Part 2: More Utility Classes 519


The Observer Interface


To observe an observable object, you must implement theObserverinterface. This interface
defines only the one method shown here:


void update(ObservableobservOb, Objectarg)

Here,observObis the object being observed, andargis the value passed bynotifyObservers( ).
Theupdate( )method is called when a change in the observed object takes place.


An Observer Example


Here is an example that demonstrates an observable object. It creates an observer class,
calledWatcher, that implements theObserverinterface. The class being monitored is called
BeingWatched. It extendsObservable. InsideBeingWatchedis the methodcounter( ),
which simply counts down from a specified value. It usessleep( )to wait a tenth of a
second between counts. Each time the count changes,notifyObservers( )is called with the
current count passed as its argument. This causes theupdate( )method insideWatcherto
be called, which displays the current count. Insidemain( ), aWatcherand aBeingWatched
object, calledobservingandobserved, respectively, are created. Then,observingis added
to the list of observers forobserved. This means thatobserving.update( )will be called each
timecounter( )callsnotifyObservers( ).


/ Demonstrate the Observable class and the
Observer interface.
/


Method Description
void addObser ver(Obser verobj) Addsobjto the list of objects obser ving the invoking object.
protected void clearChanged( ) Calling this method returns the status of the invoking object
to “unchanged.”
int countObser vers( ) Returns the number of objects obser ving the invoking object.
void deleteObser ver(Obser verobj) Removesobjfrom the list of objects obser ving the invoking
object.
void deleteObser vers( ) Removes all obser vers for the invoking object.
boolean hasChanged( ) Returnstrueif the invoking object has been modified and
falseif it has not.
void notifyObser vers( ) Notifies all obser vers of the invoking object that it has
changed by callingupdate( ). Anullis passed as the second
argument toupdate( ).
void notifyObser vers(Objectobj) Notifies all obser vers of the invoking object that it has
changed by callingupdate( ).objis passed as an argument
toupdate( ).
protected void setChanged( ) Called when the invoking object has changed.

TABLE 18-7 The Methods Defined byObservable

Free download pdf