在使用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;
}
}
Run Code Online (Sandbox Code Playgroud)将工厂注入演示者.该工厂负责即时查看.将父视图传递给对话框视图存在一些问题(通常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;
}
}
Run Code Online (Sandbox Code Playgroud)您对实例化新演示者和视图的责任有何看法?我正在寻找其他人方法的实际例子.谢谢你的建议.
| 归档时间: |
|
| 查看次数: |
552 次 |
| 最近记录: |