Behavioral Patterns  «Prev  Next»
Lesson 6 Observer structure
ObjectiveWrite a TimeObserver Interface.

Write a TimeObserver Interface

The Observer pattern uses two abstract classes or interfaces: Observer and Observed (also called Subject).
The Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically.
The diagram below illustrates the structure:

  1. Each Observer object possesses an update() method which is invoked by the Observed object when the Observed object changes
  2. The Observer pattern is also responsible for telling the Observed object that it should notify the Observer object when it changes

Observer Design Pattern Structure
The Observed object must keep a list of the objects observing it. It must provide an interface for adding objects to and removing objects from that list.
Finally, it contains whatever methods that result in changes to its state. Every time the Observed state of the object changes, it cycles through the list, notifying each Observer in turn of the change.
The Observer interface declares the update method that the Observed object will invoke. This method does whatever the class wants to do as a result of the notification.

MVC within the context of Observer

In the (MVC) model-view-controller architecture the model is the real thing, and the views approximate it. Think instead of a model that poses for a painting. The model is real, and different artists can observe the same model and draw different views.
Here is what happens when a user types text into one of the windows:
  1. The controller tells the model to insert the text that the user typed.
  2. The model notifies all views of a change in the model.
  3. All views repaint themselves.
  4. During painting, each view asks the model for the current text.
This architecture minimizes the coupling between the 1) model, 2) views, and 3) controllers. The model knows nothing about the views, except that they need to be notified of all changes. The views know nothing of the controllers and it is easy to add more views to a model. It is also easy to change the controller of a view, for example to facilitate voice input.
Let us have a closer look at the notification mechanism.
  1. The model knows about a number of observers, namely, the views.
  2. An observer is an object that is interested in state changes of the model.
  3. The model knows nothing in detail about the observers except that it should notify them whenever the model data changes.

Observed Object - Exercise

In this exercise, you will write a TimeObserver interface for the course project.
Observed Object - Exercise