Applied Design Patterns with Java

Behavioral :: Observer (293) {C ch 22}


Example - Java :: Patterns\Behavioral\Observer

Pattern Concept: to provide one-to-many dependencies on data, so that when one object changes state, all of its dependents are notified and automatically updated. The Observer pattern provides a means to operate on data in different ways at the same time. The Cooper's example Observer pattern assumes the object containing the data is separated from the objects that display the data, and that these display objects observe changes in the data, as illustrated below:

The master object, and hence its data, are called the Subject; its dependent objects that display the data are called Observers. The Observers call a public method in the Subject, and the Observers also implement an interface known to the Subject:

public interface Observer {

// notify Observers that a change has occurred

public void sendNotify(String s);

}

public interface Subject {

// notify Subject of Observer's interest in data changes

public void registerInterest(Observer obs);

}

This method allows a completely opened-ended implementation of the Observer pattern. Cooper's example demonstrates the Observer pattern by two different GUI representations of the Subject data, and it uses a Java JDK JList object as an Observer. Here is the Java JDK swing subtree for JList:


Example - UML : Watch2Windows
The example maintains two Observers, a window with a list of data, and another window with a color interpretation, both governed by changes in the Subject. Note that this use of JList is an example of another Design Pattern: the MVC. All JFC components using the Observer pattern are in fact implementations of the MVC pattern too.

Here is Cooper's Class Diagram for the application using this logic, followed by the Rose equivalent:





The example Java program is called 'Watch2Windows'.

The UML diagram is above, and the list of Java files is below:

Issues and consequences of the Observer pattern include:

Catalog Behavioral Prev Next