Java Reference
In-Depth Information
Method
Description
notifyObservers
(Object arg)
Calls the
update()
method for all of the
Observer
objects in the internal record if the current object has
been set as changed. The current object is set as changed
by calling the
setChanged()
method below. The
current object and the argument passed to the
notifyObservers()
method will be passed to the
update()
method for each
Observer
object.
notifyObservers()
Calling this method is equivalent to the previous method
with a
null
argument. (See
setChanged()
method
below.)
countObservers()
The count of the number of
Observer
objects for the
current object is returned as type
int
.
setChanged()
Sets the current object as changed. You must call this
method before calling the
notifyObservers()
method. Note that this method is
protected
.
hasChanged()
Returns
true
if the object has been set as 'changed', and
false
otherwise.
clearChanged()
Resets the changed status of the current object to
unchanged. Note that this method is also
protected
.
It's fairly easy to see how these methods are used to manage the relationship between an
Observable
object and its associated observers. To connect an observer to an
Observable
object, the
Observer
object must be registered with the
Observable
object by calling its
addObserver()
method. Once
this is done the
Observer
will be notified automatically when changes to the
Observable
object
occur. An observable object is responsible for adding
Observer
objects to its internal record through
the
addObserver()
method. In practice, the
Observer
objects are typically created as objects that
are dependent on the
Observable
object and then they are added to the record, so there's an implied
ownership relationship.
This makes sense if you think about how the mechanism is often used in an application using the
document/view architecture. A document has permanence since it represents the data for an
application. A view is a transient presentation of some or all of the data in the document, so a
Document
object should naturally create and own its
View
objects. A view will be responsible for
managing the interface to the application's user, but the update of the underlying data in the
Document
object would be carried out by methods in the
Document
object, which would then notify other
View
objects that a change has occurred.
Of course, you're in no way limited to using the
Observable
class and the
Observer
interface in the
way in which we've described here. You can use them in any context where you want changes that
occur in one class object to be communicated to others. We can exercise the process in a silly example.