关于以下 Java 类:
public class GuiController {
private GuiView view;
public GuiController(GuiView view){
this.view = view;
}
//responds to user inputs to GuiView
}
public class GuiView {
//interacts with user
}
//lives in the Servlet context
public class SomeLongLifeClass {
private GuiView view;
public SomeLongLifeClass(){
this.view = new GuiView();
new GuiController(view);
}
}
由于没有外部引用,GuiController 最终会被垃圾回收吗?它不应该是因为它主动与引用的 GuiView
交互,我只是不明白为什么。
在第二个问题中,如果不是这样,还应该如何实现 View / Controller 模式?
最佳答案
事实上,是的,您的 GuiController 实例符合 GC 条件。在更实际的代码中,您可能会将 Controller 注册为 GuiView 组件的监听器(直接或间接),因此 Controller 将从 View 中引用, View 本身由 GUI 线程引用。
关于java - Java 中没有变量引用的新实例会被垃圾收集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22351864/