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

26 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

  19. Its good.. thanks for educatif.. :))

    Comment by Milan — October 1, 2012 @ 2:00 am | Reply

  20. Thank you for some other magnificent post. Where else may just anyone get that kind
    of information in such a perfect approach of writing?
    I’ve a presentation next week, and I am at the search for such information.

    Comment by medien-buehne-film.de — April 15, 2013 @ 11:56 am | Reply

  21. It’s going to be ending of mine day, except before ending I am reading this enormous piece of writing to improve my know-how.

    Comment by call option method — May 16, 2013 @ 6:58 pm | Reply

  22. I’m amazed, I must say. Rarely do I encounter a blog that’s both educative and amusing, and let me tell you, you have hit the nail on the head.
    The issue is something that not enough men and women
    are speaking intelligently about. Now i’m very happy that I stumbled across this in my search for something regarding this.

    Comment by call options — May 30, 2013 @ 12:49 am | Reply

  23. I think what you posted made a great deal of sense.
    But, what about this? suppose you composed a
    catchier title? I am not saying your content is not solid.

    , but suppose you added a post title that grabbed folk’s attention? I mean Tutorial On Observer Pattern | Khangharoth is a little vanilla. You might glance at Yahoo’s home
    page and watch how they create article titles to grab viewers to click.
    You might try adding a video or a related picture or two to get readers interested about what you’ve written. In my opinion, it might bring your posts a little bit more interesting.

    Comment by call options — May 31, 2013 @ 11:01 pm | Reply

  24. Thanks for sharing your thoughts on fsdfsdf.

    Regards

    Comment by call options — June 2, 2013 @ 2:38 am | Reply

  25. These are really impressive ideas in about blogging. You have touched some good things
    here. Any way keep up wrinting.

    Comment by put option — June 3, 2013 @ 11:38 am | Reply

  26. Thank you for this code, very clear to understand (I searched the web for hours…)

    Comment by MJ1 — January 5, 2014 @ 10:51 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a reply to put option Cancel reply

Blog at WordPress.com.