Suppose I have two classes: A
with property A.a
, B
with property B.b
.
Some properties in A
depend on B.b
, but A.a
does not depend on B.b
.
Some properties in B
depend on A.a
, but B.b
does not depend on A.a
.
I would like A
to be notified of changes in B.b
, and B
to be notified of changes in A.a
. If I use the standard observer pattern:
public class A implements B.Observer {..}
public class B implements A.Observer {..}
I get a compiler error:
cyclic inheritance involving B (or A).
I realize that this could cause an infinite loop in general, but it doesn't in this case. For example, if A.a
changes, A
would notify B
. But since A.a
has no effect on B.b
, there is no return notification to A
and no cycle.
I appreciate that Java
is trying to prevent general problems, but I need to implement this somehow. Any suggestions?
Use the publish-subscribe pattern where each of your classes is both a publisher and a subscriber.
interface Publisher {
void addSubscriber(Subscriber sub);
}
interface Subscriber {
void handle (Object event);
}
class A implements Publisher, Subscriber {...}
class B implements Publisher, Subscriber {...}
If you don't mind using some JavaFX techniques, then you should look into properties and binding which will allow you to something similar to what you already have but this time no compiler errors