我试图在Java中创建一个遵循MVC模式的游戏。我的问题是我找不到一种好方法将存储在模型中的游戏地图传递给视图中的绘画组件。
我的代码的一个非常简化的版本:
型
public class Model {
//0,0,200,200,0.... are read from a file and stored in a List
//inside the model.
private List<Integer> gameMap;
public Model(){
gameMap = new ArrayList<Integer>();
}
视图
public class View extends JFrame{
private class GameBoard extends JComponent{
public void paintComponent(Graphics g){
//Now I need the values from the List in the Model to my
//View for the g.drawRect methods
g.drawRect(0, 0, 200, 200);
}
}
控制器
public class Controller {
public Controller(View view, Model model) {
}
最简单的方法当然是在视图中有一个静态列表并做一个Model.gameMap...但这会打破MVC模式。
如果我通过在控制器中执行类似操作在视图中保留游戏地图的副本,它仍然是 MVC 吗?
view.gameMap = model.gameMap;
如果要遵循 MVC 模式,则视图不能具有对模型的任何引用。
为了不破坏 MVC,控制器(将读取模型)必须将该信息提供给视图。
<小时 />您的代码确实简化了,但正确的示例(尊重 MVC)是:
型
public class Model {
//GameMap info is read from a file and stored in a List
//inside the model.
private List<Integer> gameMap;
public Model(){
gameMap = new ArrayList<Integer>();
//Read file and fill gameMap
}
public List<Integer> getGameMap(){
return gameMap;
}
}
视图
public class View extends JFrame{
private Controller controller;
public View(Controller controller){
this.controller = controller;
}
private class GameBoard extends JComponent{
public void paintComponent(Graphics g){
//Now I need the values from the List in the Model to my
//View for the g.drawRect methods
List<Integer> gameMapInfo = controller.getGameMap();
//Perform custom drawing using this object's values
//g.drawRect()...
}
}
控制器
public class Controller {
private View view;
private Model model;
public Controller(View view, Model model) {
this.view = view;
this.model = model;
}
public List<Integer> getGameMap(){
return model.getGameMap();
}
视图保存控制器的引用,当需要绘制时,会向控制器询问执行此操作所需的信息。控制器询问模型,并将信息返回到视图。
你可以简单地通过声明这样一个方法来传递绘制上下文
private Object drawContext;
public void updateDrawContext(Object drawContext){
this.drawContext = drawContext;
}
public void paintComponent(Graphics g){
drawContext(g);
g.drawRect(0, 0, 200, 200);
}
private void drawContext(Graphics g){
// your custom draw code
// just an example, not real code:
for(OPbject o: drawContext.getItems() ){ // your custom draw code
o.draw(g);
}
}
理想情况下,您将在interface MVCView
中声明方法void updateDrawContext(Object drawContext)