[java] Extending Observer/Observable when already extending something
Hi,
I was wondering if there is any easy way to use Observer/Observable when I already extend something different since Java doesn't allow multiple inheritance. I have thought an Interface would work but not sure how to go about that unless I can just have my class implement a Interface that requires an Observer/Observable method to be defined.
Any help would be greatly appreciated.
class YourClass extends YourOtherClass implements Observer
If that's not what you're looking for, please describe what you want to do in more detail :)
Here's how I usually implement Observer pattern in Java (grossly simplified):
interface InterestingListener { void somethingInterestingHappened();}class SomethingInteresting { List<InterestingListener> listeners = new ArrayList<InterestingListener>(); public void addListener(InterestingListener l) { listeners.add(l); } public void removeListener(InterestingListener l) { listeners.remove(l); } private void notifyListeners() { for (InterestingListener l : listeners) { l.somethingInterestingHappened(); } }}
And a typical usage:
... SomethingInteresting foo = new SomethingInteresting(); foo.addListener( new InterestingListener() { void somethingInterestingHappened() { System.out.println("Interesting!"); } }); ...
The reason for rolling your own instead of using the provided Observer/Observable is for more precise control, like not having to downcast the argument, ability to provide different arguments, maybe of primitive types or whatever you need, and also not having to pass the source object if you don't need it.
[Edited by - lightbringer on November 25, 2008 8:53:58 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement