Java Reference
In-Depth Information
if (users != watching)
throw new IllegalArgumentException();
UserState state = (UserState) whichState;
if (watching.loggedIn(state)) // user logged in
addUser(state); // add to my list
else
removeUser(state); // remove from list
}
// ...
}
Each
Eye
object watches a particular
Users
object. When a user logs in
or out,
Eye
is notified because it invoked the
Users
object's
addObserver
method with itself as the interested object. When
update
is invoked, it
checks the correctness of its parameters and then modifies its display
depending on whether the user in question has logged in or out.
The check for what happened with the
UserState
object is simple here.
You could avoid it by passing an object describing what happened and
to whom instead of passing the
UserState
object itself. Such a design
makes it easier to add new actions without breaking existing code.
The
Observer
/
Observable
mechanism is a looser, more flexible analogue to
access protects you from undesired concurrency. The observation mech-
anism enables any relationship to be built between two participants,
whatever the threading model. Both patterns have producers of inform-
ation (
Observable
and the invoker of
notify
) and consumers of that in-
formation (
Observer
and the invoker of
wait
), but each one fills a differ-
ent need. Use
wait
/
notify
when you design a thread-based mechanism,
and use
Observer
/
Observable
when you need something more general.
Exercise 22.4
: Provide an implementation of the
Attributed
interface
that uses
Observer
/
Observable
to notify observers of changes.