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:
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:
The controller tells the model to insert the text that the user typed.
The model notifies all views of a change in the model.
All views repaint themselves.
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.
The model knows about a number of observers, namely, the views.
An observer is an object that is interested in state changes of the model.
The model knows nothing in detail about the observers except that it should notify them whenever the model data changes.