Observer Pattern

Summary

  • The Observer pattern defines a relationship between objects so that when one changes its state, all the others are notified accordingly. There is usually an identifiable single publisher of new state, and many subscribers who wish to receive it
  • The Observer pattern supports both push and pull models.
  • The Observer pattern is widely used in blog sites and various software systems, like Flickr, cyber-dating web sites, and Microsoft Updates are a few of the places where it is applied.
  • The Observer pattern also has a formal face as the "publish/subscribe" model and the "Model-View-Controller" (MVC) architectural pattern.

Class diagram: (see Observer Pattern code review)

Observer Pattern class diagram of sample code download

Usage

Use the Observer pattern when:

  • There are aspects to an abstraction that can vary independently.
  • Changes in one object need to be propagated to a selection of other objects, not all of them.
  • The object sending the changes does not need to know about the receivers.