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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With