title: How can circular dependencies be avoided when callbacks are used?
body: <p>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.</p>
  
  <pre><code>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); } }
  }
  </code></pre>