GofPatterns GofPatterns

Behavioral Patterns  «Prev 

Structure of the Observer Pattern

Observer pattern consisting of Observed, Observer, and ConcreteObserved

  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.
Use the Observer pattern in any of the following situations:
  1. When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
  2. When a change to one object requires changing others, and you don't know how many objects need to be changed.
  3. When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.

You might think of the Observer pattern as an alternative to the MVC. At the root of the Observer are Subject and Observer interfaces. The Subject holds a given state and the observers subscribe to the subject to be informed of the current state. You can think of it as a blog with many subscribers—one set of information is routinely updated for a variety of users who subscribe or regularly read the blog. Each time the blog is changed (its state changes), all of the subscribers are informed. Figure 14-1 shows the Observer class diagram.

Figure 6-6: Observer class diagram

One of the more interesting and possibly perplexing features of this pattern is the Subject's methods. While the italicized title "Subject" title indicates an interface (an abstract class in this case), abstract methods are italicized as well. However, as you can see in Figure 6-6, none of the methods are italicized. It is clear which methods Subject generates, and the Notify() method even has pseudocode to help out. You will find several different implementations of the Observer pattern.