Suppose I have two classes: A
with property Aa
, B
with property Bb
.
Some properties in A
depend on Bb
, but Aa
does not depend on Bb
.
Some properties in B
depend on Aa
, but Bb
does not depend on Aa
.
I would like A
to be notified of changes in Bb
, and B
to be notified of changes in Aa
. 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 Aa
changes, A
would notify B
. But since Aa
has no effect on Bb
, 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
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.