Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observing multiple observables while avoiding instanceof operator in java?

If I have an object that I want to be able to observe several other observable objects, not all of the same type. For example I want A to be able to observe B and C. B and C are totally un-related, except for the fact that they both implement Observable.

The obvious solution is just to use "if instanceof" inside the update method but that quickly can become messy and as such I am wondering if there is another way?

like image 266
startoftext Avatar asked Dec 03 '10 22:12

startoftext


1 Answers

A clean solution would be to use (anonymous) inner classes in A to act as the Observers. For example:

class A {
    public A(B b, C c) {
        b.addObserver(new BObserver());
        c.addObserver(new CObserver());
    }

    private class BObserver implements Observer {
        // Logic for updates on B in update method
    }

    private class CObserver implements Observer {
        // Logic for updates on C in update method
    }
}

This will allow you to add BObserver/CObserver instances to however many Bs and Cs you actually want to watch. It has the added benefit that A's public interface is less cluttered and you can easily add new inner classes to handle classes D, E and F.

like image 122
Cameron Skinner Avatar answered Nov 16 '22 00:11

Cameron Skinner