This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Java in General and the fly likes what is   Observable class  and Observer interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "what is   Observable class  and Observer interface" Watch "what is   Observable class  and Observer interface" New topic

what is Observable class and Observer interface

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
what are these Observable class and Observer interface?
what they are for why these clasess are introduced by java :roll: ?
what is the actual use?
is this classes are really important in building a webapplication?

till now i havn't seen any example for this
can any one provide me an example for this program?

thanks to all


SCJP 1.4
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

There is a design pattern called Observer. It is useful to notify several objects (Observer) when something has happened to one instance (Observable).

It is commonly used in Ajax to notify several objects when an event (like onclick) occurs.
What you basically do is :
1. Have an Observable class
2. Have a few Observer classes
3. Register the Observers to the Observable object (addObserver)
4. Call notifyObserver when you want to notify all the observers that something has happened

[My Blog]
All roads lead to JavaRanch
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

I've made a little sample. I forgot to say that setChanged has to be called for all observers to be notified.

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42954
I like the example

Observer/Observable are about the simplest event distribution method you can use that decouples source (Obervable) and listener (Observer); there's nothing about it that is particularly applicable to web applications. Its drawback is that Observer must be extended, which may or may not be acceptable in a particular situation. But since there isn't much to the Observer class (look at its source code and you'll see what I mean), you can just as easily incorporate its functionality into your own class. (Note that you can pass additional information to the Observer through the second parameter of the update method.)

I've used this mechanism a few times in MVC scenarios (with Observable being the model and Observer being the controller), but these days I'd prefer custom event classes with an event register/unregister mechanism.
[ August 29, 2006: Message edited by: Ulf Dittmer ]
subject: what is Observable class and Observer interface