Implementing the Observer Pattern

Overview

The event monitor pattern fulfills many needs, but it falls short in many other ways, as documented in Chapter 10, "Exploring the Event Monitor Pattern." Some of the shortcomings in the Event Monitor pattern include the following:

The Observer pattern corrects many of the shortcomings of the Event Monitor pattern. The Observer pattern has many variations, each with subtle distinctions that are not necessarily "standardized." For the purpose of this book, the Observer pattern allows clients to register for event notifications with some object or service that contains an interesting state that may change. When a change in state occurs to the target object, the target object notifies the interested observers of the change.

One variation of the Observer pattern, the Publish/Subscribe pattern, uses an intermediate object or service for event registration and delivery rather than the primary object containing state. Chapter 12, "Implementing the Publish/ Subscribe Pattern," covers the Publish/Subscribe pattern in more detail.

The event monitor has a distinct shortcoming when addressing the liveliness inherent in a system. One aspect of a system's overall liveliness is how quickly it reacts to user input or to underlying changes in data. The event monitor puts an artificial bound on the liveliness of the application, coupling the ability to react to a change to the polling cycle of the event monitor. By implementing the Observer pattern, the target Web Service takes responsibility for delivering events to clients rather than forcing the clients to determine when events occur. Now, a client receives an event notification as soon as it possibly can, outside of a polling cycle, thus increasing the overall liveliness of the application.

This change in implementation also turns the responsibility of detecting a change from the observer of an object to the object itself. This responsibility lies naturally with the object because it already knows the change as it modifies the data. It also solves several problems created by forcing the client to determine when an event occurs in a server component. For example, a client does not have to worry about missing an important event. On the application hosting side, a Web Service does not have to be concerned with servicing hundreds or thousands of queries when no changes have occurred to the Web Service.

The Observer pattern is so important in practice that the Java language contains classes to help you implement the pattern. The book Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995) contains the original documentation for the Observer pattern. This chapter goes over the fundamentals of the Observer pattern and its implementation in a Web Service paradigm.