gpt4 book ai didi

java - java中的MVC模式,观察者中不止一种更新方法

转载 作者:太空宇宙 更新时间:2023-11-04 07:47:51 24 4
gpt4 key购买 nike

我正在用mvc设计编写一个带有gui的国际象棋游戏。

第 1 步:弹出主菜单,然后选择游戏模式。

第 2 步:选择后,主菜单将关闭,并打开一个包含棋盘和棋子的新窗口,然后用鼠标进行游戏。

第 1 步;我使用 actionEvent 并检查您单击的按钮的字符串。例如,您有“标准游戏”按钮,然后模型设置数据板并通知观察者(= View )。

第 2 步;我使用 mouseEvent 并检查相对坐标 x/y,模型执行其操作并决定是否可以移动该棋子。

我希望 View 中有两种更新方法,一种用于第 1 步,另一种用于第 2 步。目前它总是进入第一次更新。

// this is in the model, initializing once you chose a game mod,
// this is for the first step.
public void initializeGame(String givenString){
abstractGame = factoryGame.createGame(givenString);
abstractGame.startPlaying(boardTest);
setChanged();
notifyObservers(5);
}

// this is in the model, doing stuff, this is for the second step.
public boolean checkGivenCoordinates(int sourceRow, int sourceColumn, int destinationRow, int destinationColumn) throws IncorrectCoordinatesException, IncorrectColorException, InvalidMoveException
{
if(abstractGame.checkCorrectCoordinates(sourceRow, sourceColumn, destinationRow, destinationColumn) == true)
{
abstractGame.checkMove(sourceRow, sourceColumn, destinationRow, destinationColumn);
int [] changeView = {sourceRow, sourceColumn, destinationRow, destinationColumn};
System.out.println("Model : in the move ");
setChanged();
notifyObservers(changeView);
return true;
}
else
throw new IncorrectCoordinatesException();
}


// Called from the Model
public void update(Observable obs, Object obj) { // this is the one it always goes to now.

//who called us and what did they send?
System.out.println ("First update View : Observable is " + obs.getClass() + ", object passed is " + obj.getClass());
} //update()

// Called from the Model
/* this is for step 2, but is not invoked.
The array I send holds 4 ints, source row/column and destination row/column.
this is what I do in model just prior to notifying,
supposed to go to step 2's update method,
but as stated, it doesnt.
*/
public void update(Observable obs, int[] obj) {

//who called us and what did they send?
System.out.println ("Second update View : Observable is " + obs.getClass() + ", object passed is " + obj.getClass());
graphBoardView.setMove(obj[0], obj[1], obj[2], obj[3]);

} //update()

所以,

1) 我可以在一个类中进行多次更新吗?

2)如果是这样,我如何直接通知正确的更新方法?

3)如果 q1 不可能,我该如何绕过这个?

4) 是否是对象 obj 导致它总是转到第一个?

提前致谢,艾瑞尔。

最佳答案

在同一个类中,确实可以有多个同名但参数不同的方法。

当编译器无法确定要使用哪个方法(如果存在歧义)时,您可以看到您所看到的情况 - 请记住数组也是一个对象

通过一个简单的测试用例,它应该可以工作:

new Test().update(new Observable(), new int[]{1, 2});
new Test().update(new Observable(), new Object());

调用正确的方法。

你如何调用你的方法?

关于java - java中的MVC模式,观察者中不止一种更新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14980262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com