Observer

 
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 Observable). A before & after structure are given below.
Object relations: before & after
Structure Observer pattern structure
Consequences Creates classes.
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 the Object class.
  • 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