Java Reference
In-Depth Information
UserState state = new UserState(name);
loggedIn.put(name, state);
setChanged();
notifyObservers(state);
}
public void logout(UserState state) {
loggedIn.remove(state.name());
setChanged();
notifyObservers(state);
}
// ...
}
A
Users
object stores a map of users who are logged in and maintains
UserState
objects for each login. When someone logs in or out, all
Ob-
server
objects will be passed that user's
UserState
object. The
notifyOb-
servers
method sends messages only if the state changes, so you must
invoke
setChanged
on
Users
; otherwise,
notifyObservers
would do nothing.
Here is how an
Observer
that maintains a constant display of logged-in
users might implement
update
to watch a
Users
object:
import java.util.*;
public class Eye implements Observer {
Users watching;
public Eye(Users users) {
watching = users;
watching.addObserver(this);
}
public void update(Observable users, Object whichState)
{