【问题标题】:How do I separate classes for MVC design pattern in Java (KeyListener separate from JFrame)?如何在 Java 中分离 MVC 设计模式的类(KeyListener 与 JFrame 分离)?
【发布时间】:2012-07-30 09:21:26
【问题描述】:
我正在使用 MVC 设计模式在 java 中制作一个打砖块游戏,但我不知道如何使 Controller 类与视图类分开。它应该是足够简单的任务,我想在控制器类中创建 keyListener,同时将所有视觉内容保留在 View 类中(我可以自己处理模型)。出于某种原因,我找不到如何做到这一点。现在我有一个扩展 JFrame 并实现 keylistener 的视图类。
我更喜欢使用代码发布 2 个小类的答案。
【问题讨论】:
标签:
java
model-view-controller
design-patterns
keylistener
【解决方案1】:
在 Swing 中,View 和 Controller 大部分是相同的类,例如JTable(视图和控制器)+TableModel(模型)。
如果您想要一个清晰的分离,您可以查看JGoodies,它是 Swing 的数据绑定框架,但我不确定它是否是游戏的最佳解决方案。
当然你可以实现自己的Logic Layer,例如
public interface GameStateListener {
public void playerPositionChanged(Player p, Position oldPos, Position newPos);
}
// Stores the current state of the game
public class DefaultGameState implements IGameState {
public void addGameStateListener(GameStateListener) {...}
}
// Contains the logic of the game
public class DefaultGameLogic implements IGameLogic {
public DefaultGameLogic(IGameState gameState) {...}
public void doSomething(...) { /* update game state */ }
...
}
// displays information of the game state and translates Swing's UI
// events into method calls of the game logic
public class MyFrame extends JFrame implements GameStateListener {
private JButton btnDoSomething;
public MyFrame(IGameLogic gameLogic, IGameState gameState) {
// Add ourself to the listener list to get notified about changes in
// the game state
gameState.addGameStateListener(this);
// Add interaction handler that converts Swing's UI event
// into method invocation of the game logic - which itself
// updates the game state
btnDoSomething.addActionListener(new ActionListener() {
public void actionPerformed() {
gameLogic.doSomething();
}
});
}
// gets invoked when the game state has changed
// (might be by game logic or networking code - if there is a multiplayer ;) )
public void playerPositionChanged(Player p, Position oldPos, Position newPos) {
// update UI
}
}
使用 Java 的 Observable 和 Observer 接口并不是很方便,因为您需要找出被观察对象的哪些属性发生了变化。
因此使用自定义回调接口是实现这一点的常用方法。