Search This Blog

Monday, January 16, 2006

THE OBSERVER PATTERN

Like the Singleton Pattern, which was covered in the first half of this tip, the Observer pattern is a popular design pattern used in Java programs. The pattern is a behavioral design pattern. It defines a way for classes to be loosely coupled and for one class (or many) to be notified when another is updated. Basically, this means that when something happens in one place, you notify anyone who is observing and that is interested in that one place.

There are two ways to look at the Observer pattern. The first way involves the Observer and Observable classes found in the java.util package. The second way follows the JavaBeans component model of registering event listeners with components.

Prior to the creation of the JavaBeans event model, the Observer and Observable classes described an implementation of the Observable pattern. In other words, the classes have been around since the 1.0 version of the Java platform. There is nothing technically wrong with the classes and they are still present in the libraries. The classes still could be used to implement the Observable pattern, but the second model, the JavaBeans component model, is typically used. One significant problem in using the classes to implement the Observable pattern is that you have to extend Observable. This forces a class hierarchy structure that might not be possible in the single-inheritence world of the Java platform.

The JavaBeans component model of registering event listeners involves a series of add and remove methods, where the listener type is embedded in the method name. For instance, to observe the selection of a button, you register an ActionListener with the component:
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
...
}
};
JButton button = new JButton("Pick Me");
button.addActionListener(listener);
That really is all there is to the Observer pattern for the system-defined classes. You implement a listener interface, attach it to the Subject of the observation, and wait. The Subject is what is observed. It is responsible for remembering who is observing. In the JavaBeans component model case, the interface to attach and detach the Observer objects is the add/remove listener naming pattern. When the state of the Subject changes, it notifies the Observer objects.

One of the main objectives of the pattern is to enable the loose coupling of the Subject and Observer. When the JButton is selected, instead of calling a specific method of a fictitious subclass named ButtonNotification, the notification is abstracted out into an interface that anyone can implement. The JButton doesn't care what class the attached Observer (listener) is. In fact, the button doesn't care if the implementing class is modified. All it cares about is that the Observer implements a listener.

There are a number of complications you need to watch out for when using the Observer pattern. First is the possibility of a memory leak. A reference to the Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector. Be aware of this possibility and remove observers where appropriate. Also note that the set of Observer objects is maintained in an unordered collection -- at least when registering event listeners. You don't necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object A must be notified first, followed by object B, you must introduce an intermediary object to enforce the ordering. Simply registering the observers in a particular order will not enforce their order of notification.

Another area of the Java platform that models the Observer pattern is the Java Message Service (JMS), with its guaranteed delivery, non-local distribution, and persistence, to name a few of its benefits. The JMS publish-subscribe messaging model allows any number of subscribers to listen to topics of interest. When a message for the published topic is produced, all the associated subscribers are notified.

There are many other places in the Java platform that model the Observer pattern -- the pattern is frequently used throughout the Java platform.

Since the 1995 publication of the
Design Patterns book by the Gang of Four, other books have been published that offer different perspectives on the same patterns and introduce additional patterns. Two of the more popular titles are:

Head First Design Patterns
Refactoring to Patterns

Other books, such as Patterns of Enterprise Application Architecture are available for those interested in more targeted design pattern coverage -- in this case, for enterprise applications. For more information on design patterns in general, see its Wikipedia entry.

This Tech Tips issue is dedicated to the memory of John Vlissides, one of the original Gang of Four authors. He passed away November 2005.

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.