Jump to content
  • Advertisement
Sign in to follow this  
Lothia

[java] Extending Observer/Observable when already extending something

This topic is 3612 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!