
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
352
Chapter 16
CHAPTER 16
The Observer Design Pattern
[The Observer pattern defines] a one-to-many dependency between objects so that when
one object changes state, all its dependents are notified and updated automatically.
——from Design Patterns: Elements of Reusable Object-
Oriented Software (the so-called GoF book discussed in
Chapter 15)
Effectively, the Observer pattern is an all-purpose event-broadcasting mechanism. It
lets a class broadcast generic updates to registered listeners, much as you could ask
your local movie retailer to call you when a DVD you’re interested in arrives. It could
be used in anything from a mail application (when a new email is received) to a video
game (when an enemy dies).
In the Observer pattern, changes in the state of one object (the subject) are broadcast
to other interested objects (the observers). Each observer object indicates that it is
interested in receiving broadcasts by registering with the subject. When the subject
changes, it tells its current list of observers that it changed.
The Observer pattern is perfect for rendering multiple representations of a single
body of data. For example, consider a weather-reporting application with a class,
WeatherReporter, that stores the latest weather report. On screen are two representa-
tions of the weather ...