简体   繁体   中英

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?

A clean solution would be to use (anonymous) inner classes in A to act as the Observer s. 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 B s and C s 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> Map<Class<? extends Event>, EventHandler> in your listener. Similar, but no explicit 'instanceof' operator. It gets replaced with containsKey() in a map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM