我需要 View 来保存对 Controller 的引用,因为它需要将 Controller 注册为事件监听器。 我需要 Controller 来保存对 View 的引用,因为单击按钮后,我需要能够在列表中获取选定的文件。 (我有一个文件列表和一个“添加集群”按钮,因此单击该按钮时我需要获取所选文件)
所以简而言之,我有:
Controller controller(view);
View view(controller);
我确定这里有一些糟糕的设计,我只是想不出如何避免它..
最佳答案
我不确定您使用的是什么 Java 技术,但在 GWT 应用程序中 - 并使用 MVP 模式 - 不需要 View 引用 Controller : Controller (或演示器)之间的所有通信而View是通过View实现的一个接口(interface)来制作的。在您的特定情况下,您的代码应如下所示:
定义一个显示界面:
public interface Display {
public void registerEventListener(Listener aListener)
public List getSelectedFiles ()
}
让 View 实现该接口(interface):
public class View implements Display{
//The method implementations
}
并在 Controller 中进行所有必要的绑定(bind):
public class Controller{
private Display view;
public Controller(){
//Or use some DI technology
this.view = new View();
//Get a Listener implementation, maybe an Anonymous Inner Class
this.view.registerEventListener(getListener());
}
public void processFiles(){
List files = view.getSelectedFiles();
//Do the processing here
}
}
关于java - MVC——循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865289/