advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorial: Keeping Your Java Objects Informed with the Observer Design Pattern:

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

How to Add Java Applets to Your Site

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.

 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 43
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Google Hopes Chrome Will Help, Not Hurt Firefox
Remember Figlets? They're Back With Zend
Microsoft Readies an App Store Competitor?
Google: Chrome Browser Will Make Money
Sam Ramji: Microsoft's Man in Open Source
Google to Shake Up Browsers With Own Launch
Mozilla's Ubquity Mashup: For The Masses?
iPhone Users Just Want to Have Fun
Oops! I Fixed the Linux Kernel
Jim Zemlin: The New Center of Linux Gravity

Code Around C#'s Using Statement to Release Unmanaged Resources
Writing Functional Code with RDFa
BitLocker Brings Encryption to Windows Server 2008
Network Know-How: Exploring Network Algorithms
Create a Durable and Reliable WCF Service with MSMQ 4.0
The Baker's Dozen: 13 Tips for SQL Server 2008 and SSRS 2008
Book Excerpt: Microsoft Expression Blend Unleashed
Develop a Mobile RSS Feed the Easy Way
State of the Semantic Web: Know Where to Look
A 3D Exploration of the HTML Canvas Element

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES