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
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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With