284 | Chapter 8: Observer Pattern
introduced, adding a class as part of the application is as easy as creating the class
and subscribing it to the subject.
The following key features characterize the Observer pattern:
- Data consistency between loosely coupled but related and interacting objects.
- Data receptors (observers) can subscribe and unsubscribe to data.
- Single source (subject) sends state change information.
- Any number of subscribing observers can subscribe to subject.
To understand the importance of consistency, consider a speech at the United
Nations. Suppose the representative from China gives a speech on new trade poli-
cies. That information will have to be translated from Chinese to all of the different
languages represented at the UN. A good Observer pattern sends the speech infor-
mation from a single source (subject), to the interpreters (observers), presented in a
language that different language users can understand. If each observer got the
speech from a different source, the chances of inconsistency increase dramatically,
and if inconsistent data were received, the Chinese trade policies could be
misconstrued.
The two central objects in the Observer model are thesubjectandobserver. The sub-
jectnotifiesthe observer of any state changes. This design relies onobject composi-
tioninstead of inheritance as the primary technique for reuse. In this case, the subject
delegates operations to the observer. This process is expanded and explained in the
sectionKey OOP Concepts Used with the Observer Pattern, later in this chapter.
The Observer Model
The Observer outlined in the class diagram notation shows two key elements: sub-
ject and observer. The subject interface provides the method for notifying the observ-
ers of state changes. Likewise, the subject holds the methods for subscribing and
unsubscribing. The capacity to subscribe objects leaves the door wide open for new
objects to be added to the list of objects receiving data. The subject set of methods all
delegate to the observer. The observer, by contrast, simply needs a method for
updating states. The concrete subject uses the update method of the observer in the
notification method implemented from the subject interface. Also, the concrete sub-
ject may have both getters and setters for state-related changes. The concrete
observer must implement the updating method. However, it may also have methods
for subscribing or unsubscribing, most likely the former, leaving the unsubscribing
methods up to the concrete object instances or state conditions. Figure 8-2 shows the
Observer class diagram:
We can break down the diagram into its four parts—subject, observer, concrete sub-
ject and concrete observer. The Subject interface sets up the key connections
between itself and the observer by establishing methods that connect and disconnect