我正在做一个Yahtzee游戏。我想为不同的情况提供构造函数。假设您无法提供想要创建新游戏的玩家的名字,我只想创建"未命名玩家1","未命名的玩家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");
}
}
当然,根据评论中写的错误,这不起作用。
有解决方法吗?我需要一个工厂模式吗?
答案 0 :(得分:9)
是的,有一个相当简单的方法,至少在这种情况下:创建一个静态方法,为你准备构造函数参数。从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
上的任何实例方法。