The Observer Pattern/Publish and Subscribe
As you might guess from its name, the Observer pattern is used to observe the state of an object. A variant on this pattern is Publish and Subscribe, where the observed object "publishes" some event or events (e.g., a clock says "I announce every second") and other objects (the observers) "subscribe" to those events.
To keep things simple, we'll refer to the two patterns together as the Observer pattern; it really is just a matter of perspective (are you observing me, or am I publishing my events for you to subscribe to?).
The Observer pattern defines a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and have a chance to respond to the change.
Fundamental to this pattern is the notion that objects (known as observers or listeners) are registered (or self-register) to observe an event that may be raised by the observed object (known as the subject), as seen in Figure 8-15.
Figure 8-15. UML class diagram for the Observer pattern
To make this a bit more concrete, we'll borrow an example from the real world. Many of you probably read the blog Slashdot.org, pictured in Figure 8-16. (If you don't already, you'll probably start now.) Some of you might even subscribe to Slashdot's daily digest. This site illustrates almost everything there is to know about the Observer pattern: Slashdot publishes ...
Get Programming .NET 3.5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.