[java] Extending Observer/Observable when already extending something

Started by
1 comment, last by Lothia 15 years, 5 months ago
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.
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]
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.

This topic is closed to new replies.

Advertisement