我正在尝试学习 MVP,但有些事情让我困惑;如果Presenter使用视图作为界面,那么View就不能只是控件的简单渲染。想象一下,尝试编写一个打字练习游戏,其中单词是随机生成到 UI 中的,用户必须在单词从屏幕上落下时输入单词。
所以视图将具有如下方法:
public interface View {
addWord(String word, double x, double y); // or possibly (Word word)
moveWord(String word, double distance);
removeWord(String word);
setScore(int score);
registerKeyListener(KeyListener listener);
// other stuff
}
但最终 VIEW 必须负责创建自定义控件。这里省略了很多代码,但希望这足以说明我的意思。例子:
public class SwingView {
private JPanel thePanel;
private Map<String, WordComponent> currentWords = new HashMap<>();
public SwingView() {
thePanel = new JPanel(new WordLayout());
// other stuff
}
public void addWord(String word, double x, double y) {
WordComponent newWord = new WordComponent(word);
currentWords.put(word, newWord);
Point2D.Double point = new Point2D.Double(x, y);
thePanel.add(newWord, point);
}
public void removeWord(String word) {
WordComponent theWord = currentWords.get(theWord);
thePanel.remove(theWord);
}
}
View 实现已经有了逻辑。它维持着一个Map
of its WordComponent
s。我在这里有两个自己的班级,WordLayout implements LayoutManager2
, and WordComponent extends JLabel
(或其他东西,但这将是更多代码)。
理论上,演示者应该对 Swing 一无所知,因此我可以使用可能会记录到控制台或其他内容的模拟进行单元测试。但简单地管理 Swing 对象本身就是一项工作。或者,如果我想将此应用程序转换为 Tomcat 网页该怎么办?现在上课ServletView
正在管理移动单词的 AJAX 调用。它依赖于 AJAX 框架,这甚至将更多的工作卸载到View
.
摘要: 是View
实现应该有管理自己组件的“逻辑”吗?
后续:我上面写的代码可能甚至不会响应,因为Model
和Presenter
不在事件调度线程上工作(或者,它们在事件调度线程上工作,这可能更糟)。将显示更新移交给事件调度线程的代码去了哪里?或者,应该Presenter
在事件调度线程上?
Edit:我突然想到一个想法。拥有一个特定于平台的子演示者is了解实现细节,例如您是否使用 Swing 还是其他东西。
Edit2:还有一个问题,基于@DuncanJones 的回答。想象一下,我想要添加逻辑来使游戏可调整大小并根据新大小缩放所有内容的大小。这个逻辑是否存在于View
,或在Presenter
?