The Observer pattern defines a relationship between objects so that when one changes its state, all the others are notified accordingly. There is usually an identifiable single publisher of new state, and many subscribers who wish to receive it.
Once more, we'll look to the world of the Internet for an illustration. The Observer pattern leads us to blogs, which are web sites where people write about technical topics, their travels, their lives, and so on. Each blog site is maintained by a single blogger. People who come to read about the information put out by a blogger and find it interesting can subscribe to be informed each time a new blog entry is posted. Bloggers don't always post regularly; days or weeks might go by between entries. Therefore, it is more efficient for the blogger to alert interested parties rather than for those parties to constantly poll the blog site.
Figure 9-8 shows a typical blog site. On the right is an "Email alerts" link. In terms of the Observer pattern, those who wish to observe what is going on can click on this link to sign up to be alerted whenever there is a change on the site.
Figure 9-8. Observer pattern illustration—a blog site
The Observer pattern is, like the Mediator pattern, composed of
two classes. The
Subject is a class
whose objects change their state at an independent rate.
Observers may indicate that ...