gpt4 book ai didi

Java Refactor 导致循环引用

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:34:53 26 4
gpt4 key购买 nike

我在桌面应用程序中有这种代码

这只是一个包含按钮之类的 JPanel。

class ApplicationPanel {

private Listener listener;

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

这会将事件添加到上面 JPanel 中的控件。

class Listener {

private ApplicationPanel panel;

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

调用者代码是这样的

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

如果我尝试应用依赖注入(inject)和工厂(稍后将更改为 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;
}
}

调用者代码是这样的如您所见,此代码中存在循环依赖解决此问题的最佳方法是什么?

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

}

最佳答案

查看 this blog post关于主题; guice 足够聪明,给定您在 guice 模块中提供的绑定(bind),可以检测循环引用,然后使用临时代理来解决注入(inject)问题。

关于Java Refactor 导致循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4124578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com