在使用MVP架构设计应用程序时,我提出了关于实例化视图的问题。在我的情况下,演示者必须与视图完全分离,以便轻松更改UI工具包。只要只有一个视图,一切都很清楚。当需要动态创建视图时,我的问题出现了。例如,当单击新按钮时,弹出窗口要求用户填写一些数据。我有两个解决方案,但我对其他人感到好奇。我在下面给出了我的方法的示例代码。
让我们的父视图实例化对话框视图并将其返回到父级演示者,其中对话框演示者也实例化。我不喜欢具体视图必须实例化另一个视图的想法。我觉得实例化不是视图的责任。
public interface View {
public void setPresenter(Presenter presenter);
public void showView();
}
public interface NewDialogView implements View {
/* ommited ordinary getters/setters for view */
}
public interface MainWindowView implements View {
/* ommited ordinary getters/setters for view */
public NewDialogView createNewDialog();
}
public interface Presenter {
public View getView();
}
public class NewDialogPresenter implements Presenter {
protected NewDialogView view;
public MainWindow(NewDialogView view) {
this.view = view;
this.view.setPresenter(this);
}
public View getView() {
return view;
}
}
public class MainWindowPresenter implements Presenter {
protected MainWindowView view;
public MainWindow(MainWindowView view) {
this.view = view;
this.view.setPresenter(this);
}
public void newButtonClicked() {
NewDialogView newDialogView = view.createNewDialog(); // too much responsibility?
NewDialogPresenter newDialogPresenter = new NewDialogPresenter(newDialogView);
newDialogView.showView();
/* then let's NewDialogPresenter deal with user input */
}
public View getView() {
return view;
}
}
将工厂注入演示者。该工厂负责即时查看。将父视图传递给对话框视图存在一些问题(通常GUI框架需要它)。还有相当多的设置。
// Just presenter approach differs and there is no create method in view interface.
public interface MainWindowView implements View {
/* ommited ordinary getters/setters for view */
}
public class MainWindowPresenter implements Presenter {
protected MainWindowView view;
protected NewDialogViewFactory newDialogViewFactory;
public MainWindow(MainWindowView view) {
this.view = view;
this.view.setPresenter(this);
}
public void newButtonClicked() {
NewDialogView newDialogView = newDialogViewFactory.createNewDialog(view); // should pass a parent view here or not?
NewDialogPresenter newDialogPresenter = new NewDialogPresenter(newDialogView);
newDialogView.showView();
// then let's NewDialogPresenter deal with user input
}
public View getView() {
return view;
}
public void setNewDialogViewFactory(NewDialogViewFactory newDialogViewFactory) {
this.newDialogViewFactory = newDialogViewFactory;
}
}
您对实例化新演示者和视图的责任有何看法?我正在寻找其他人方法的实际例子。 谢谢你的建议。
答案 0 :(得分:0)
在我的情况下,我实际上从不创建视图(包括对话框)。我假设任何时候都不会出现多个对话框,因此我使用GIN实例化对话框并将对话框注入到演示者中。然后,演示者只需要更改对话框(包括处理程序)的属性并显示它。这允许我使用GIN在一个地方管理所有视图(和演示者)的创建。