Wednesday 10 February 2010

OO concepts: Observer pattern

Introduction
In this post I sum up the Observer pattern, an interesting OO pattern very useful in many situations.

Description
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.


The Observer pattern describes how to establish these relationships. The key objects in this pattern are subject and observer. A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state. In response, each observer will query the subject to synchronize its state with the subject’s state.

This kind of interaction is also known as publish-subscribe. The subject is the publisher of notifications. It sends out these notifications without having to know who its observers are. Any number of observers can subscribe to receive notifications.

Basic Pattern



Complex Pattern



Consequences
The advantages are:
§          You can vary and independently reuse classes for the Subject and Observer objects.
§          The abstract classes (or interfaces) are coupled together. Therefore, the coupling is looser than if the concrete classes were coupled.
§          You can easily add Observer objects without a single change to the Subject object.
The disadvantages are:
§          An observer system can become flooded with updates if the granularity of the update is too fine or its frequency too high. This is a critical problem in distributed systems.
§          The observer system often calls the subject when it receives a notification. This can create a bottleneck, preventing the timely update of the other observer systems.

References
Gamma, Helm, Johnson, and Vlissides. Design Patterns. Elements of Reusable Object-Oriented Software. Addison-Wesley.

No comments:

Post a Comment