I need to perform some tasks on object1
when some state change happens on object2
.
I was trying to use observable pattern in android, I mean to use Observer and Observable classes, so object1
implements Observer and object2
extends Observable. Unfortunately, object2
already extends from another class, so I can't define it as an extension of Observable.
Is there another alternative to use this pattern? Maybe other classes that allow me to perform this behavior?
Thanks.
There's a popular implementation of the Mediator pattern that relies on Observer. The mediator object plays the role of publisher, and the components act as subscribers which subscribe to and unsubscribe from the mediator's events. When Mediator is implemented this way, it may look very similar to Observer.
So, what's the alternative we have ? You can use PropertyChangeEvent and PropertyChangeListener from java. beans package. PropertyChangeListener replaces Observer , but what should I extend/implement in place of Observable ?
In Java, you may have come across classes called observer and observable, which have been commonly used to implement the observer pattern in Java. However, these were deprecated in Java 9 and are no longer recommended for use.
In the observer pattern, the source of data itself (the Subject) knows who all are its observers. So, there is no intermediate broker between Subject and Observers. Whereas in pub-sub, the publishers and subscribers are loosely coupled, they are unaware of even the existence of each other.
Simply add to object2
a field of type Observable
to which observers are added and on which notifyObservers()
is called when something changes.
This is what's meant by "favor composition over inheritance".
Extending the built-in Observable class is a rather bad choice to implement the observer pattern as it disrupts your class hierarchy, but you know that already.
A better way would be to define your own Observable
interface and let your class implement it. You will also need a Listener
interface for the listener classes
The methods you would need in your Observable
interface are addListener(Listener listener)
and removeListener(Listener listener)
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