Click here to Skip to main content
12,301,394 members (63,028 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


39 bookmarked

The Observer Design Pattern

, 18 Dec 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
A quick tour of the Observer Design Pattern.


I will attempt to explain what is one of the most widely used Design Patterns: Observer Pattern.

Problem domain: Implementing the Publisher/Subscriber scenario. We need a mechanism which allows us to notify subscriber objects whenever the publisher object changes state.

There is one publisher or subject class and one or more subscriber or observer classes.



In order for observers to receive a notification, they must implement some kind of update method which the subject can call whenever it changes state. The observers must have the freedom to register and un-register from subscription to the subject at any point in time.

The subject contains the stuff. So, whenever the stuff changes, observers need to be notified.

Here, the Observer Pattern comes to the rescue.


We need to create two Interfaces: Subject and Observer. The interface for the subject contains the register, unregister, and notify method signatures, as follows:

public interface Subject
  public void register(Observer o);
  public void unregister(Observer o);
  public void notify();

The interface for the observer contains an update method signature:

public interface Observer
    public void update(int value);

Now, let us assume that we are building a sample stock market gadget app. Here, the subject is the one which has the 'stuff', i.e., the stock market quotes. The observers are different classes which display the latest stock quotes to the user.

Let us have classes representing the subject/observer relationship: the StockMarket class being the subject, and we have three different observer classes: GoogleStockGadget, YahooStockGadget, and MSNStockGadget.

The StockMarket class must implement the Subject interface:

public class StockMarket : Subject
  // A Collection to keep track of all Registered Observers
  ArrayList observers = new ArrayList();

  // Stores latest stock quote (example is purposely simplistic)
  int newValue = 0;
  public void setValue(int v)
    newValue = v;
  public void register(Observer o)

  public void unregister(Observer o)
    int i = observers.indexOf(o);

  public void notify()
    for (int i=0;i < observers.size();i++)
      Observer ob = (Observer)observers.get(i);

The observers: GoogleStockGadget, YahooStockGadget, and MSNStockGadget, must implement the Observer interface.

Note that the observer classes must maintain a reference variable of type Subject.

public class GoogleStockGadet : Observer
   int latestValue = 0;
   Subject stockMarket; // Subject reference variable

   // Note how subject is passed in the constructor of Observer
   public GoogleStockGadet(Subject subject)
    stockMarket = subject;
    stockMarket.register(this); // Registering itself to the Subject

   public void update(int value)
    latestValue = value;

   public void display()
     System.out.println("Latest Quote=" + latestValue);

   public void unsubscribe()

Similarly, YahooStockGadget and MSNStockGadget implement the observer interface.

Now, let's see how we make it all work in the main program.

public class MainProgram
  public static void Main(string[] args)
    //Initialize Subject
    StockMarket stockMarket =  new StockMarket();
    int latestQuote = 0;

    // Initialize Gadgets..Note the subject being passed in Constructor
    GoogleStockGadget googleGadget = new GoogleStockGadget(stockMarket);
    MSNStockGadget msnGadget =  new MSNStockGadget(stockMarket);
    YahooStockGadget yahooGadget = new YahooStockGadget(stockMarket);

    // Code for Getting latest stock 
    // ....
    // ....

    // Updating all Registered Observers

    //GoogleGadget decides to unregister/unsubscirbe


With that, I end my article. Remember, the Observer Design Pattern solves the common problem of notifying several objects (i.e., Observers) about changes in the state of one principle object (or the Subject).

This, being my first article, might not be perfect, but hopefully, it has helped you in better understanding the concepts of the Observer Design Pattern.

Happy coding!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer
United States United States
Just a budding .net developer.

You may also be interested in...

Comments and Discussions

SuggestionMy 5 & Suggestion Pin
Kishor Deshpande4-Feb-13 22:45
memberKishor Deshpande4-Feb-13 22:45 
GeneralMy vote of 4 Pin
Shashank Bisen15-Jul-12 20:09
memberShashank Bisen15-Jul-12 20:09 
Generalsome enchancements Pin
Alexander_Ukhov20-Dec-09 23:45
memberAlexander_Ukhov20-Dec-09 23:45 
GeneralIf you like this Article - Check out the Reactive Extensions Pin
Rune Baess18-Dec-09 12:51
memberRune Baess18-Dec-09 12:51 
GeneralRe: If you like this Article - Check out the Reactive Extensions Pin
Steven Relis20-Dec-09 1:38
memberSteven Relis20-Dec-09 1:38 
GeneralUnregistering dangling references Pin
supercat918-Dec-09 9:18
membersupercat918-Dec-09 9:18 
AnswerRe: Unregistering dangling references Pin
Anides18-Dec-09 9:43
memberAnides18-Dec-09 9:43 
GeneralSome errors Pin
Bob Geiger18-Dec-09 3:28
memberBob Geiger18-Dec-09 3:28 

Thanks for the attempt that you've made so far in explaining the Observer design pattern.

Your code has quite a few misspellings unfortunately. Frown | :(

public class GoogleStockGadet implements Observer

It's like you have the code half written in C# (which is how the article is tagged) and the other half in VB. Implementation of an abstract class or interface in C# uses the colon followed by the list of interfaces or the abstract class that the class is implementing. Also most standard naming conventions dictate that you should prefix your interface name with an uppercase I making it easily understood at a glance that the implementation is an interface. You also create the class "GoogleStockGadet" but then later instantiate it with "GoogleStockGadget" which is not implemented in your code.

public class GoogleStockGadget : IObserver

Public instance methods should also begin with an uppercase character using standard method naming conventions.

If your intention was just pseudocode, then you should at least follow 1 standard convention so that implementing your examples is possible. Unfortunately none of the code provided compiles at all.

Thanks, and keep submitting!
GeneralRe: Some errors Pin
Anides18-Dec-09 4:19
memberAnides18-Dec-09 4:19 
GeneralRe: Some errors Pin
Andre Luiz V Sanches18-Dec-09 6:41
memberAndre Luiz V Sanches18-Dec-09 6:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160525.2 | Last Updated 18 Dec 2009
Article Copyright 2009 by Anides
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid