Swing では、View
とController
はほとんど同じクラスです。たとえば、JTable (ビューとコントローラー) + TableModel (モデル) です。明確な分離が必要な場合は、Swing のデータ バインディング フレームワークであるJGoodies
を
見ることができますが、それがゲームに最適なソリューションになるかどうかはわかりません。
もちろん、独自のものを実装することもできます。
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インターフェイスを使用するのは、監視対象オブジェクトのどのプロパティが変更されたかを調べる必要があるため、あまり便利ではありません。
したがって、カスタム コールバック インターフェイスを使用することが、これを実装する一般的な方法です。