Observers and Observables

Problem

When an interest rate changes unknown numbers and types of objects that depend on that rate need to be notified (newspapers, investment brokers, government agencies, etc.)

We could hardwire the rate with the knowledge of all the objects that can be notified, but this means the rate would need to be constantly modified.

We could have interested parties constantly poll the rate, but this would generate a lot of wasteful traffic if the rate changed infrequently.

Solution

Java provides an Observable class that maintains a list of objects that implement Java's Observer interface, which requires an update method.

The Observable's notifyObservers method calls the update method of each registered observer.

Here's the design:

Implementation

There are two types of observers: dedicated and non-dedicated. In the following template Bank is dedicated and Broker is non-dedicated.

Bank.java

Application

The Model-View-Controller pattern is a popular architecture for desk top applications.

The Model-View-Controller pattern is often refined by making the model an observable and the views observers:

This solves the View Notification Problem: Without a reference from Model to View, how will views know when the model has been updated and that they should refresh themselves?

Application

In Java controls such as buttons, text fields, and menu items play the role of observables, while listeners play the role of observers.

References

The Observer-Observable template is a version of the Publisher Subscriber pattern:

Publisher-Subscriber Pattern

The Java Event Model