Java Reference
In-Depth Information
22.3.
Observer
/
Observable
The
Observer
/
Observable
types provide a protocol for an arbitrary number
of
Observer
objects to watch for changes and events in any number of
Observable
objects. An
Observable
object subclasses the
Observable
class,
which provides methods to maintain a list of
Observer
objects that want to
know about changes in the
Observable
object. All objects in the "interes-
ted" list must implement the
Observer
interface. When an
Observable
ob-
ject experiences a noteworthy change or an event that
Observer
objects
may care about, the
Observable
object invokes its
notifyObservers
method,
which invokes each
Observer
object's
update
method.
The
Observer
interface consists of a single method:
public void
update(Observable obj, Object arg)
This method is invoked when the
Observable
object
obj
has a
change or an event to report. The
arg
parameter is a way to
pass an arbitrary object to describe the change or event to the
observer.
The
Observer
/
Observable
mechanism is designed to be general. Each
Ob-
servable
class is left to define the circumstances under which an
Observer
object's
update
method will be invoked. The
Observable
object maintains a
"changed" flag which subclass methods use to indicate when something
of interest has occurred.
protected void
setChanged()
Marks this object as having been changed
hasChanged
will now
return
true
but does not notify observers.
protected void
clearChanged()
Indicates that this object is no longer changed or has notified
all observers of the last change
hasChanged
will now return
false
.