what is Observable class and Observer interface (Java in General forum at Coderanch) (original) (raw)

posted 18 years ago

what are these Observable class and Observer interface?
what they are for why these clasess are introduced by java 🥐 ?
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

regards
cinux

A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
SCJP 1.4

posted 18 years ago

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é

Sheriff

Posts: 14691

Eclipse IDE VI Editor Ubuntu

posted 18 years ago

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

[My Blog]
All roads lead to JavaRanch

posted 18 years ago

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 ]