在java中避免使用instanceof运算符时观察多个observable? [英] Observing multiple observables while avoiding instanceof operator in java?

查看:213
本文介绍了在java中避免使用instanceof运算符时观察多个observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个对象,我希望能够观察其他几个可观察对象,而不是所有相同类型。例如,我希望A能够观察B和C.B和C完全不相关,除了它们都实现Observable这一事实。

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.

显而易见解决方案只是在更新方法中使用if instanceof,但很快就会变得混乱,因此我想知道是否还有其他方法?

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?

推荐答案

与之前的建议类似,您可以将更新更改为。

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);

您要观察的每种类型。不幸的是,您需要知道Observable的具体类型。但是,您可以更改反射以允许接口等。

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.

这篇关于在java中避免使用instanceof运算符时观察多个observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆