Design Patterns

Observer



Design Pattern Type: Behavioral

GoF Statement of Intent:


Defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.
Brief Overview:



The basic idea is the Publisher-Subscriber relationship. One object (the subject) maintains a list of its "dependents" (the observers) and notifies them automatically of any state changes which they want to know about. The subject notifies them by calling one of their methods. This method may just be to pass a reference to itself so that the observers can then "call back" to get the data they need.
UML Diagram:

Discussion and In-class Example:

In the Observer Design Pattern we used the example of the Weather-O-Rama simulation in which a weather monitoring instrument (represented by the WeatherData class) was connected up to any number of weather data sensors (known in the Observer pattern as Subjects) from which it acquired data and to any number of display devices (known in the Observer Pattern as Observers) to which it passed data from the sensors.

The WeatherData object, its sensors, and display devices were following the principle of keeping classes loosely coupled. That is, the WeatherData object knew virtually nothing about what the sensors were or how they functioned. It only knew that they provided it with streams of data. The WeatherData object also knew virtually nothing about the display devices or how they displayed their data. It only knew that they were interested in receiving one or more of the streams of data that the WeatherData object was getting.