Observing multiple observables while avoiding instanceof operator in java?

穿精又带淫゛_ 提交于 2019-11-27 15:13:09

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/4350508/observing-multiple-observables-while-avoiding-instanceof-operator-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!