在调用 this(arguments) 之前构造函数链接和准备参数

Constructor chaining and preparing arguments before calling this(aguments)

我正在制作 Yahtzee 游戏。我想为不同的情况提供一个构造函数。假设您懒得提供要创建新游戏的玩家的名字,我只想创建 "Unnamed Player 1"、"Unnamed Player 2" 等

以下是我尝试这样做的方法:

public class YahtzeeGame {
    private List<Player> players = new ArrayList<>();

    public YahtzeeGame(String[] playerNames) {
        for (String playerName : playerNames) {
            players.add(new Player(playerName));
        }
    }

    public YahtzeeGame(int numberOfPlayers) {
        String[] playerNames = new String[numberOfPlayers];
        for (int i = 0; i < numberOfPlayers; i++) {
            playerNames[i] = "Unnamed player " + (i+1);
        }
        this(playerNames); // ERROR: "Constructor call must be the first statement in a constructor.
    }

    public YahtzeeGame(String playerName) {
        this(new String[] {playerName});
    }

    public YahtzeeGame() {
        this("Unnamed player");
    }
}

根据评论中的错误,这当然行不通。

有办法解决这个问题吗?为此我需要工厂模式吗?

是的,有一个相当简单的解决方法,至少在这种情况下是这样:创建一个将为您准备构造函数参数的静态方法。从 this 表达式调用它:

public YahtzeeGame(int numberOfPlayers) {
    this(getUnnamedPlayers(numberOfPlayers));
}

private static String[] getUnnamedPlayers(int numberOfPlayers) {
    String[] playerNames = new String[numberOfPlayers];
    for (int i = 0; i < numberOfPlayers; i++) {
        playerNames[i] = "Unnamed player " + (i+1);
    }
    return playerNames;
}

请注意,它必须是静态的,因为您也不能在链式构造函数之前调用 this 上的任何实例方法。