我试图用 Java 创建一个遵循 MVC 模式的游戏。我的问题是我想不出一个好方法将存储在模型中的游戏 map 传递给 View 中的绘制组件。
我的代码的一个非常简化的版本:
模型
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);
}
}
Controller
public class Controller {
public Controller(View view, Model model) {
}
最简单的方法当然是在 View 中有一个静态列表并执行 Model.gameMap ……但这会破坏 MVC 模式。
如果我通过在 Controller 中执行类似操作在 View 中保留游戏 map 的副本,它仍然是 MVC 吗?
view.gameMap = model.gameMap;
最佳答案
如果你想遵循MVC模式, View 不能引用模型 .
为了不破坏 MVC, Controller (将读取模型)必须向 View 提供该信息。
您的代码确实简化了,但正确的示例(尊重 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()...
}
}
Controller 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();
}
View 保存了 Controller 的引用,当需要绘制时,会向 Controller 询问它需要的信息。 Controller 询问模型,并将信息返回给 View 。
关于java - MVC 和图形组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37583470/