THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
protected voidsetChanged()

Marks this object as having been changedhasChanged will now return
truebut does not notify observers.

protected voidclearChanged()

Indicates that this object is no longer changed or has notified all observers of
the last changehasChanged will now return false.

public booleanhasChanged()

Returns the current value of the "changed" flag.

When a change occurs, the Observable object should invoke its setChanged method and then notify its
observers with one of the following methods:


public voidnotifyObservers(Object arg)

Notifies all Observer objects in the list that something has happened, and
then clears the "changed" flag. For each observer in the list, its update
method is invoked with this Observable object as the first argument and
arg as the second.

public voidnotifyObservers()

Equivalent to notifyObservers(null).

The following Observable methods maintain the list of Observer objects:


public voidaddObserver(Observer o)

Adds the observer o to the observer list if it's not already there.

public voiddeleteObserver(Observer o)

Deletes the observer o from the observer list.

public voiddeleteObservers()

Deletes all Observer objects from the observer list.

public intcountObservers()

Returns the number of observers in the observer list.

The methods of Observable use synchronization to ensure consistency when concurrent access to the
object occurs. For example, one thread can be trying to add an observer while another is trying to remove one
and a third is effecting a change on the Observable object. While synchronization is necessary for
maintaining the observer list and making changes to the "changed" flag, no synchronization lock should be
held when the update method of the observers is invoked. Otherwise it would be very easy to create
deadlocks. The default implementation of notifyObservers takes a synchronized snapshot of the current
observer list before invoking update. This means that an observer that is removed while
notifyObservers is still in progress will still be notified of the last change. Conversely, an observer that

Free download pdf