The Observer Pattern
The description of a pattern has four parts:
- The pattern's intent
- The pattern's motivation
- The pattern's implementation
- The consequences of the pattern's use
Intent
We again reference the GoF book to describe the intent of the Observer design pattern:
"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."
Some authors call observers "dependents" because of the one-to-many dependency relationship. Other authors refer to observers as "subscribers" because one object publishes notifications and one or more observer objects subscribe to the notifications. All these points of view can be helpful, so in this article, we use the terms "observer," "subscriber," and "dependent" interchangeably.
Motivation
The motivation for the Observer design pattern is to avoid tight coupling. For example, consider a stock quote application. The application sends quotes to its subscribers. A first attempt to write the stock quote application might look like this:
public class StockData
{
private String symbol; // the stock symbol
private float close; // the closing stock price
private float high; // the high stock price for the day
private float low; // the low stock price for the day
private int volume; // the amount of stocks traded
// getter and setter methods defined here...
public void sendStockData(String symbol,float close,float high,float low,long volume)
{
symbol = getSymbol();
close = getClose();
high = getHigh();
low = getLow();
volume = getLow();
tradingFool.update(symbol,close,high,low,volume);
bigBuyer.update(symbol,close,high,low,volume);
}
}
Here, the code assumes that tradingFool and bigBuyer, are just two of potentially many class instances interested in obtaining the latest stock data. To analyze this code, it uses a single method, update(), with all interested parties as shown below:
tradingFool.update(symbol,close,high,low,volume);
bigBuyer.update(symbol,close,high,low,volume);
The trouble is, you'll eventually want to add additional parties to the sendStockData() method:
stockBoy.update(symbol,close,high,low,volume);
To add stockBoy, you have to recompile the StockData class. That's not good. The StockData class shouldn't be so tightly coupled to things like stockBoy and bigBuyer. Instead, StockData should be ready to provide information to anyone (well, to a large, ever-changing group of "anyones").
Implementation
Figure 1 shows the official UML diagram for the Observer pattern.

Figure 1. The official UML diagram for the Observer design pattern.
Here's a walk-through of the parts of the UML diagram:
- The
ConcreteSubject class implements the Subject interface.
- The
Subject interface declares the methods for observers to register and remove themselves with a ConcreteSubject. The interface also contains a method to notify all registered observers. A particular subject can have many observers.
- The
Observer interface declares a method for obtaining updates from the Subject. The subject publishes an update when its state changes.
- The
ConcreteObserver class implements the Observer interface.
- Each
ConcreteObserver object has its own instance of the ConcreteSubject class. The subject variable (in the ConcreteObserver class) refers to this instance.
In the ongoing stock quote example, each concrete observer (TradingFool, BigBuyer, and StockBoy) implements the update() method declared in the Observer interface. The ConcreteSubject calls each observer's update() method, sending updated information to each concrete observer. In turn, each concrete observer uses the updated information in whatever way it sees fit.
Figure 2 shows a refactored UML diagram for the stock quotes application using the Observer design pattern.

Figure 2. The refactored UML diagram for the stock quote application.
The source code for this refactored diagram is in Listings 1 to 5, and the client code is in Listing 6.
You may benefit from walking through some of the code in Listings 1 through 6. Listing 6 creates an instance of the StockData class. The StockData object maintains an observers list (an ArrayList that holds all registered observers). The client code creates instances of TradingFool and BigBuyer. As these instances construct themselves, they add themselves to the observers list. That is, tradingFool and bigBuyer register to receive stockData subject notifications.
new TradingFool(stockData);
new BigBuyer(stockData);
The constructor of each concrete observer contains the following lines to accomplish the registration:
stockData.attach(this);
The attach() method in the StockData class (Listing 2) adds the interested observer to the ArrayList.
At this point, a call to the setStockData() method is a trigger for the subject to notify all registered observers that something has changed. In this application, the setStockData() method passes in the stock symbol, the closing price, the high price for the day, the low price for the day, and the total volume of shares traded. Once these variables have their values, it calls sendStockData() to publish the news.
The first attempt to write a StockData class had a ten-line sendStockData() method. In comparison, the sendStockData() method in Listing 2 is a one-liner. This new version of sendStockData() simply calls the notifyObservers() method. You may be wondering why the new class keeps this silly-looking sendStockData() method. There's a good reason for this. If the sendStockData() method has already been established in other client code, then bypassing the sendStockData() method could break that client code. Thus, the one-line sendStockData() method changes the implementation while maintaining the established interface.
Figure 3 shows a run of the StockQuotes program (the code in Listing 6).
-- Stock Quote Application --
Trading Fool says...
JUPM is currently trading at $16.10 per share.
Big Buyer reports...
The lastest stock quote for JUPM is:
$16.10 per share (close).
$16.15 per share (high).
$15.34 per share (low).
481,172 shares traded.
Trading Fool says...
SUNW is currently trading at $4.84 per share.
Big Buyer reports...
The lastest stock quote for SUNW is:
$4.84 per share (close).
$4.90 per share (high).
$4.79 per share (low).
68,870,233 shares traded.
Trading Fool says...
MSFT is currently trading at $23.17 per share.
Big Buyer reports...
The lastest stock quote for MSFT is:
$23.17 per share (close).
$23.37 per share (high).
$23.05 per share (low).
75,091,400 shares traded.
Figure 3. The output of the stock quote application.
The code in Listings 1 through 6 hinges upon a very important principle (quoted from the GoF book):
"Strive for loosely coupled designs between objects that interact."
When you follow this principle, objects interact with each other, but they don't know each other's intimate details. With the Observer design pattern, the subject knows only that its registered subscribers implement the Observer interface. The subject merrily sends updated data to any of its observers. The observers can come and go as they please and nothing but the client code needs to know about the comings and goings. Using this loosely coupled design, you can build applications that can adapt easily to change. You've minimized (if not eliminated) the dependencies among objects.
Listings 1 - 6
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|