Khangharoth

April 7, 2006

Tutorial On Observer Pattern

Filed under: Java,Software Design — khangharoth @ 12:18 am

Well to start off …Observer pattern is used when An object needs to notify other object(s) if it changes. .
So observer pattern has

1) Subject or Source : on which any action will happen.

2) One or more Observers : Whom Source needs to notify if any change has taken place .

Algorith Used In Observer Pattern :

1) Source have some properties say private String name, private float price;
2) Source has a collection List say ArralList or Vector .This contains refrences of all the Observers who had registerd with source to get Notified.
3) Source has a addObserver(Observer o) method so all objects which implements Observer interface can get registerd to listen the Notification.
4)Now if any changes will be done on price ,name Source will call notifyObservers() and from the collection list Source knows which all objects needs to be notified.

A sample code will be like

package observer;

import java.util.Observable;

/**
* A subject to observe!
*
*/

public class ConcreteSubject extends Observable {
 private String name;

 private float price;

 public ConcreteSubject(String name, float price) {
  this.name = name;
  this.price = price;
  System.out.println("ConcreteSubject created: " + name + " at + price");
 }

 public String getName() {
  return name;
 }

 public float getPrice() {
  return price;
 }

 public void setName(String name) {
  this.name = name;
  setChanged();
  notifyObservers(name);
 }

 public void setPrice(float price) {
  this.price = price;
  setChanged();
  notifyObservers(new Float(price));
 }
}

———————————————————–

package observer;

import java.util.Observable;
import java.util.Observer;

public class NameObserver implements Observer {
 private String name;

 public NameObserver() {
  name = null;
  System.out.println("NameObserver created: Name is " + name);
 }

 public void update(Observable obj, Object arg) {
  if (arg instanceof String) {
   name = (String) arg;
   System.out.println("NameObserver: Name changed to " + name);
  } else {
   System.out.println("NameObserver: Some other change to subject!");
  }
 }
}

————————————————————————

package observer;

import java.util.Observable;
import java.util.Observer;
/**
*
*
*
*/
public class PriceObserver implements Observer {
 private float price;

 public PriceObserver() {
  price = 0;
  System.out.println("PriceObserver created: Price is " + price);
 }

 public void update(Observable obj, Object arg) {
  if (arg instanceof Float) {
   price = ((Float) arg).floatValue();
   System.out.println("PriceObserver: Price changed to " + price);
  } else {
   System.out.println("PriceObserver: Some other change to subject!");
  }
 }
}

————————————————————————————-

package observer;
/**
*
*/
public class TestObservers {
 public static void main(String args[]) {

  // Create the Subject and Observers.
  ConcreteSubject s = new ConcreteSubject("Corn Pops", 1.29f);
  NameObserver nameObs = new NameObserver();
  PriceObserver priceObs = new PriceObserver();

  // Add those Observers!
  s.addObserver(nameObs);
  s.addObserver(priceObs);

  // Make changes to the Subject.
  s.setName("Frosted Flakes");
  s.setPrice(4.57f);
  s.setPrice(9.22f);
  s.setName("Sugar Crispies");
 }
}

Hope this will give you some insight of Observer pattern……if you need any more help……just mail me

18 Comments »

  1. I really found your tutorial here very very
    educating. I will attempt to employ similary techniques in what I am doing.

    Thanks
    Jonas

    Comment by Jonas Okwara — April 23, 2007 @ 8:39 pm | Reply

  2. Hi Jonas ,its great that you found this informative :)

    Comment by elope — April 24, 2007 @ 3:36 am | Reply

  3. Hello

    Great book. I just want to say what a fantastic thing you are doing! Good luck!

    G’night

    Comment by tovorinok — July 5, 2007 @ 4:01 am | Reply

  4. Hi…

    Nice tutorial. It’s very useful for me.
    I have a question. I am sorry if my question is a silly question.
    Can I use this Observer in J2EE platform?
    Store the Observable and Observer object in session, do you think i will work?

    Thanks.

    Comment by pdt — April 23, 2008 @ 6:24 am | Reply

  5. The tutorial is really good. the example is a good one , self-explanatory so one can easily understand the purpose of implementing Observer patterns.

    Comment by Paromita — July 3, 2008 @ 10:29 am | Reply

  6. Nice Job

    Comment by tokhi — September 20, 2008 @ 10:26 pm | Reply

  7. I am glad that you guys found this useful.

    Comment by elope — October 9, 2008 @ 4:11 pm | Reply

  8. Excellent …. I could implement the same in our project in a minutes time.

    Comment by Baskar — October 21, 2008 @ 2:33 pm | Reply

  9. Awesome example
    Nice work

    Place a RSS Feed on ur blog so tat we can subscribe to it

    Comment by Pradeep — January 21, 2009 @ 1:11 pm | Reply

  10. good tutorial ..
    keep updating

    javanub

    Comment by javanub — January 27, 2009 @ 7:31 am | Reply

  11. Thanks a lot for this tutorial, it’s well written and easy to understand.

    Comment by James — July 7, 2009 @ 11:10 pm | Reply

  12. Very good. Its nice and quick to understand.

    Comment by Veeresh — November 2, 2009 @ 11:01 am | Reply

  13. Wow, this is so clear to me now. I don’t know why a few months ago it wasn’t…

    Comment by Weeber — November 19, 2009 @ 3:57 pm | Reply

  14. Thanks dude, works like a charm!

    Comment by dan — January 4, 2011 @ 10:20 am | Reply

  15. Great post, simple and easy to follow.

    I have question, are all the observer called simultaneously i.e by multiple thread or is it single threaded?

    Comment by AU — May 27, 2011 @ 11:31 pm | Reply

  16. Just looked at the source code for Observable and its single threaded:

    for (int i = arrLocal.length-1; i>=0; i–)
    ((Observer)arrLocal[i]).update(this, arg);

    Comment by AU — May 28, 2011 @ 12:06 am | Reply

  17. Great. INFO: All observers will be notified in LIFO order.

    for (int i = arrLocal.length – 1; i >= 0; –i)
    ((Observer)arrLocal[i]).update(this, arg);
    }

    Comment by Kaebe — October 11, 2011 @ 2:07 pm | Reply

  18. Thanks for the perfect tutorial :)

    Comment by nikhiljoshihpt — March 10, 2012 @ 12:34 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.