Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can circular dependencies be avoided when callbacks are used?

How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language.

public interface Listener {
  void callBack(Object arg);
}
public class ListenerImpl implements Listener {
  public ListenerImpl(Broadcaster b) { b.register(this); }
  public void callBack(Object arg) { ... }
  public void shutDown() { b.unregister(this); }
}
public class Broadcaster {
  private final List listeners = new ArrayList();
  public void register(Listener lis) { listeners.add(lis); }
  public void unregister(Listener lis) {listeners.remove(lis); }
  public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } }
}
like image 799
sk. Avatar asked Sep 29 '08 16:09

sk.


1 Answers

I don't see that being a circular dependency.

Listener depends on nothing.

ListenerImpl depends on Listener and Broadcaster

Broadcaster depends on Listener.

        Listener
       ^        ^
      /          \
     /            \
Broadcaster <--  ListenerImpl

All arrows end at Listener. There's no cycle. So, I think you're OK.

like image 159
Herms Avatar answered Nov 02 '22 18:11

Herms