| Purpose |
Use Observer when:
- A change to 1 object requires changing others, even when it is
not known at compile-time how many objects need to be changed.
- An object notifies other objects without compile-time knowledge of who
they are.
A conceptual example of this is a spreadsheet: changing 1 field causes others
to change. This kind of interaction is also know as publish-subscribe.
The Observer pattern requires centralizing state in a model (aka subject
or Obervable). A before & after structure are given below.
|
| Structure |
|
| Consequences |
Creates classes. Don't do this unless currently needed. |
| Implementation |
- Use the java.util.Observable class & the java.util.Observer
interface.
- The order in which notifications are delivered is unspecified.
- This notification mechanism is unrelated to threads or the wait/notify
mechanism of class Object.
- In the Observable class,
- The setChanged method logic: Marks this Observable object
as having been changed.
- The notifyObservers method logic: If this object has
changed, as indicated by the hasChanged method, then notify all of
its observers & then call the clearChanged method to indicate
that this object has no longer changed.
|
| Sample Code |
Model.java, View.java
|
| Related Patterns |
|