Java watchers causing circular inheritance

Suppose I have two classes: Awith a property A.a, Bwith a property B.b.

Some properties are Adependent on B.b, but A.anot dependent on B.b.

Some properties are Bdependent on A.a, but B.bnot dependent on A.a.

I would like to Abe notified of changes in B.band Bfor notification 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 understand that this can lead to an infinite loop as a whole, but in this case it is not. For example, if A.achanged, Anotify B. But since it A.adoes not affect B.b, there is no notification of a return on Aand the absence of a cycle.

I understand that I am Javatrying to prevent common problems, but I need to somehow implement this. Any suggestions?

+4
source share
1 answer

Use the publish-subscribe template , 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 {...}

JavaFX, , - , ,

+2

All Articles