Thursday, October 16, 2008

Design Patterns (2) - Observer

Observer :image

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

Design principles of Observer ( from head first Design Pattern Chap 2)

  1. The thing that varies in the Observer Pattern is the state of the Subject and the number and types of Observers. With this pattern, you can vary the objects that are dependent on the state of the Subject, without having to change that Subject. That's called planning ahead!
  2. Both the Subject and Observer use interfaces. the subject keeps track of objects implementing the Observer interface, while the observers register with, and get notified by the Subject interface. As we've seen, this keeps things nice and loosely coupled.
  3. The Observer Pattern uses composition to compose any number of Observers with their Subjects. These relationships aren't set up by some kind of inheritance hierarchy. No, they are set up at runtime by composition!

wiki's c++ example shows an implementation of head first's chap 2 problem. It is a nice example.

Just refer to it for deep understanding of the pattern.