Intent - Define a one-to-many dependency between
objects so that when one object changes state, all its
dependents are notified and updated automatically
Problem -
You have multiple aspects that you want to encapsulate
in separate objects, allowing you to vary them
indepedently, but you want them to be aware of each other.
When one object changing requires a change in another,
and you don't want to force a relationship of
one-to-one (or enforce any size on the relationship)
You want loosely coupled objects that can notify each
other of changes.
Solution - define a relationship between the
observer and the subject such that an observer can obtain
information about the subject, and the observer can
register itself with the subject to be notified of changes.
Participants and Collaborators
Subject
Observer
ConcreteSubject
ConcreteObserver
Consequences
Abstract coupling between Subject and Observer -
Subject knows very little about observers
Support for broadcast communication - all
registrants get information
Unexpected updates - notification could be a big deal
Implementation
Mapping subjects to their observers
Observing more than one subject - subject may need
to identify themselves.
Who triggers the update? - when should the subject notify?
Dangling references to deleted subjects - not as big
of a deal in Java, but still must be considered.
Making sure Subject state is self-consistent before
notification
Avoiding observer-specific update protocols: the
push and pull models - push all, or let observer pull
out what they only need
Specifying modifications of interest explicitly -
the observer could narrow down what they are interested in
Encapsulating complex update semantics - might need
a ChangeManager to deal with complex subject/observer
relationships and can define an update strategy
Combining the Subject and Observer classes
JDK Example: java.util.Observer and java.util.Observable