Application of the MVC concept in JAVA

Good afternoon!

As for my previous post , in order to adapt to the MVC concept, as suggested, I modified my code and included the IO class as follows:

  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() + " Guess is Wrong!");
            }
        }
    }

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

It is right? How can I improve my code? Thank.

+3
source share
2 answers

The IO class represents your view in the MVC model.

The GuessGame class has a great responsibility, this class is designed for you both for the model and for the controller, you need to separate it.

You can create a game class that has the status statusToGuess and ArrayList; for both addPlayer () and start ()

GameControlled, IO . acceptPlayers(), * startGame() *, declareWinner (Player player).

+2

i.IO . IO GraphicalIO, CommandLineIO, , .

MVC. IO GuessGame , , - . IO, .

+1

Source: https://habr.com/ru/post/1793242/


All Articles