Observing several observables when throwing an instance of a statement in java?

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

The obvious solution is to simply use "if instanceof" inside the update method, but it can quickly become messy, and so I wonder if there is another way?

+7
java observer-pattern
source share
4 answers

As in previous sentences, you can change your 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 every type you want to watch. Unfortunately, you need to know the specific concrete type of Observable. However, you can change the reflections to allow interfaces, etc.

+7
source share

The pure solution would be to use the (anonymous) inner classes in A to act like 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 instances of BObserver / CObserver to the same many B and C that you really want to see. It has the added benefit that the open interface A less cluttered, and you can easily add new inner classes to handle classes D , E and F

+12
source share

Assuming that the operations on the B / C object will be identical, and you just want to distinguish between two objects for the purpose of juggling state, you can also create a delegate object that implements the actual logic / state of observation and uses the search mechanism in your main object to get the right delegate for a particular Observable. Then forward the calls.

0
source share

Your listener can always have Map<Class<? extends Event>, EventHandler> Map<Class<? extends Event>, EventHandler> . A similar but not explicit instanceof operator. It is replaced by containsKey() on the map.

0
source share

All Articles