Java refactor caused a circular reference

I have this code in my desktop application

This is just a JPanel that contains buttons and that kind of thing

class ApplicationPanel {

   private Listener listener;

   public ApplicationPanel(){
      this.listener = new Listener(this);
   }
}

This will add the event to the control in JPanel above

class Listener {

   private ApplicationPanel panel;

   public Listener(ApplicationPanel panel){
      this.panel = panel;
   }
}

That's the caller code

public void main(String[] args){
   ApplicationPanel panel = new ApplicationPanel();
}

If I try to apply dependency injection and factory (later Guice)

class ApplicationPanel {

   private Listener listener;

   public ApplicationPanel(){
      this(new Listener());
   }

   public ApplicationPanel(Listener listener){
      this.listener = listener;
   }
}

class Listener {

   private ApplicationPanel panel;

   public Listener(){
      this(new ApplicationPanel());
   }

   public Listener(ApplicationPanel panel){
      this.panel = panel;
   }
}

The caller code is like this. As you can see, there is a circular dependency in this code. What is the best way to solve this problem?

public void main(String[] args){
   Listener listener = new Listener(panel);
   ApplicationPanel panel = new ApplicationPanel(listener);

}

Solution

View this blog post of the topic; Given the bindings you provide in the Guice module, Guice is smart enough to detect circular references and then use a temporary proxy to solve the injection problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>