gpt4 book ai didi

java - 在JAVA中应用MVC概念

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:02:23 25 4
gpt4 key购买 nike

美好的一天!

关于我的 previous post , 为了按照建议适应 MVC 的概念,我更改了代码并包含了一个 IO 类,如下所示:

  public class IO {
public void output(String msg) {
JOptionPane.showMessageDialog(null, msg);
}

public String input(String prompt) {
return JOptionPane.showInputDialog(prompt);
}

public int inputInt(String prompt) {
return Integer.parseInt(input(prompt));
}
}


public class GuessGame {

private int numberToGuess;
private ArrayList<Player> player;
private IO io = new IO ();

public void acceptPlayers(){
int num_players = io.inputInt("Enter number of players");
player = new ArrayList<Player>(num_players);
for (int i = 0; i < num_players; i++) {
player.add(new Player(io.input("Enter Player " + (i+1) + " Name: ")));
}
}

public void startGame() {
numberToGuess = (int) (Math.random() * 10);
while (true) {
for (Player curPlayer : player) {
if (curPlayer.guessNumber() == numberToGuess) {
declareWinner(curPlayer);
return;
}
io.output(curPlayer.getPlayerName() + "'s Guess is Wrong!");
}
}
}

private void declareWinner(Player player) {
io.output(player.getPlayerName() + " Wins!");
}
}

这是正确的吗?我怎样才能改进我的代码?谢谢。

最佳答案

IO 类代表您在 MVC 模型中的 View 。

GuessGame 类有很多责任,这个类是给你的模型和 Controller ,你必须把它分开。

您可以创建一个 Game 类,其状态为 numberToGuessArrayList player;以及方法 addPlayer()start()

您可以拥有一个 GameControlled 类,它具有状态 IO 类和一个 Game 类。以及方法 acceptPlayers(),*startGame()*,declareWinner(Player player)

关于java - 在JAVA中应用MVC概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5051247/

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