Behavioral Patterns  «Prev 

Motivation for the Observer Pattern

Like many other patterns, Observer is also seen outside of software engineering. For instance, suppose a lot of a bookstore customers are waiting for the latest Anne Rice novel to arrive. What's more efficient?
  1. To have each of several dozen customers come visit the store every day and bother the clerk?
    (Has it come in yet? No, it has not come in yet. Come back tomorrow.) OR
  2. to have the clerk take people's names and phone numbers on a list and call them all back when the book arrives?
Obviously it is more efficient for the clerk to keep a list. That is really all the Observer pattern is, the changing object is maintaining a list and promising to notify customers on the list when it changes.

The observer design pattern enables a subscriber to register with and receive notifications from a provider. It is suitable for any scenario that requires push-based notification.
The pattern defines a provider (also known as a subject or an observable) and zero, one, or more observers. Observers register with the provider, and whenever a predefined condition, event, or state change occurs, the provider automatically notifies all observers by calling one of their methods. In this method call, the provider can also provide current state information to observers.

Have you ever used a program that shows you two editable views of the same data, such as a (WYSIWYG) what you see is what you get and a structural view of a document? When you edit one of the views, the other updates automatically and instantaneously.You may well wonder how such a feature is programmed.
  1. When you type text into one of the windows, how does it show up in the other window?
  2. What happens if you have a third view of the same information?
The key to implementing this behavior is the (MVC) model/view/controller architecture. One object, the model, holds the information in some data structure, (for example) an array of numbers, or a tree of document parts. The model has no visual appearance at all and just holds the raw data. Several other objects, the views, draw the visible parts of the data, in a format that is specific to the view. For example, the table view displays numbers in a table. The graph view displays the same numbers in a bar chart. Finally, each view has a controller, an object that processes user interaction. The controller may process mouse and keyboard events from the windowing system, or it may contain user interface elements such as buttons and menus.