开发者

Observing multiple observables while avoiding instanceof operator in java?

If I have an object that I want to be able 开发者_Go百科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?


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.


Similar to previous suggestions you could change you update to.

public void update(Observable o, Object arg) {
  try{
    Method update = getClass().getMethod(o.getClass(), Object.class);
    update.invoke(this, o, arg);
  } catch(Exception e) {
    // log exception
  }
}

This way you can add one method

public void update(A a, Object arg);
public void update(B b, Object arg);
public void update(C c, Object arg);

for each type you want to observe. Unfortunately you need to know the exact concrete type of the Observable. However you could change the reflections to allow interfaces etc.


Assuming that the operations on object B/C would be identical and you merely want to distinguish between the two objects for state juggling purposes, you could also create a delegate object which implements the actual observation logic/state and use a lookup mechanism in your main object to retrieve the right delegate for the particular Observable object. Then forward the calls.


You can always have a Map<Class<? extends Event>, EventHandler> in your listener. Similar, but no explicit 'instanceof' operator. It gets replaced with containsKey() in a map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜