Sign in to follow this  
Lothia

[java] Extending Observer/Observable when already extending something

Recommended Posts

Lothia    102
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.

Share this post


Link to post
Share on other sites
Stani R    1070
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]

Share this post


Link to post
Share on other sites
Lothia    102
That is excellent thank you. Yeah my problem had been I didn't want to extend Observable. Thanks again.
It appears you can implement them the same way you do actionListeners in some cases.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this