Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why property change listener instead of observable

I was having problems with class design until i found out about observable (using observer design pattern) and thus created a small application using it which solved my problem. I was happy and proud that I had used a good principle to sovle a problem.

Now i am about to start my main application and have just read this

Making a JFrame and Observable Object

Why is the poster advised against the use of observable and instead told to use propertychangelistenr? Is there any issues with using observable?

Regards

like image 957
Biscuit128 Avatar asked Nov 07 '11 09:11

Biscuit128


People also ask

What is property change listener?

A PropertyChangeListener is a functional interface from java. beans package. It has one abstract method propertyChange() and gets called when a bound property is changed. This method takes a PropertyChangeEvent argument that has details about an event source and the property that has changed.

What is property change listener in Java?

public interface PropertyChangeListener extends EventListener. A "PropertyChange" event gets fired whenever a bean changes a "bound" property. You can register a PropertyChangeListener with a source bean so as to be notified of any bound property updates.

Why is Java observable deprecated?

Ans: The Observable class and the Observer interface have been deprecated in Java 9 because the event model supported by Observer and Observable is quite limited, the order of notifications delivered by Observable is unspecified, and state changes are not in one-for-one correspondence with notifications.

Can an Observer be an observable?

This class represents an observable object, or "data" in the model-view paradigm. It can be subclassed to represent an object that the application wants to have observed. An observable object can have one or more observers. An observer may be any object that implements interface Observer.


2 Answers

Observer and Listener pattern are very similar. But Observer has a weakness: all observables are the same. You have to implement the logic that is based on instanceof and cast object to concrete type into Observable.update() method.

Listeners are different. There are a lot of listener types. For example mouse listener, keyboard listener etc. Each one has several callback methods (i.e. keyPressed(), keyReleased() etc). So, you never have to implement the logic that should answer the question "is it my event" into the event handler.

I think that this is why listener model is preferable.

like image 144
AlexR Avatar answered Sep 25 '22 13:09

AlexR


DejanLekic and others have probably by now realized, that Observable is not an interface. That is the whole problem with Java.util.Observable!

The user of Observable has to inherit from it, and nothing else.

Consider Java.RMI or Listener events.

like image 36
DVious Avatar answered Sep 25 '22 13:09

DVious