The Observer pattern is a design pattern that is used to observe the state of an object in an application. The observed object allows other objects to register and unregister as observers. The observers are notified when specific events that they are observing are fired. The observed object has three distinct methods, which are outlined next.
Register Observers Overview
The Observer pattern essentially allows an unlimited number of objects to observe or listen to events in the observed object (or subject) by registering themselves. After observers are registered to an event, the subject will notify them when the event is fired. The subject handles this by storing an observer collection and iterating through it when the event occurs in order to notify each observer.
Notify Observers Overview
When an event is fired in the subject, the observers are notified via the methods they provide to the observer when they are registered. Each observer specifies its own notify method and defines what happens when the notification occurs. For instance, you may have an object that registers to an error-handling object and specifies a notify method that handles displaying the error to the user. On the other hand, you may also have a completely different object that specifies a notify method, that sends an email to the developer each time an error occurs in the web application. The power of this pattern is in the fact that both of these objects can be registered and notified by the same subject.
Unregister Observers Overview
If an object no longer wants to be notified by the subject it is registered with, it can unregister itself. There are a number of instances in which this method is useful, one of which is when you do not want an object to be notified more than one time. After an object has been notified, it can unregister itself and the subject will remove it from the observer collection. For example, imagine that you want to wait to fire a method until another method has occurred. If it follows the Observer pattern, you can register to this method and wait for notification before moving forward. Take a look at Figure 16.1 for an example.
Figure 16.1. The Observer pattern allows multiple objects to observe one event and be notified when that event is invoked.
As you can see, the Observer pattern can affect numerous objects with only one event. In this chapter, we will create an error-handling object that we will call the ErrorManager. This object will follow the Observer pattern and notify any registered objects if an error occurs.