Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to the Observable Pattern?

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.

like image 416
forumercio Avatar asked Dec 01 '11 15:12

forumercio


People also ask

What pattern is most similar to the observer design pattern?

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.

What can I use instead of observable in Java?

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 ?

Is observer pattern obsolete?

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.

Is Pubsub same as observer pattern?

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.


2 Answers

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".

like image 189
Michael Borgwardt Avatar answered Oct 07 '22 04:10

Michael Borgwardt


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)

like image 29
kostja Avatar answered Oct 07 '22 03:10

kostja