有多种方法可以从构造函数中设置成员变量。我实际上是在讨论如何正确设置最终成员变量,特别是一个由助手类加载条目的映射。
public class Base {
private final Map<String, Command> availableCommands;
public Base() {
availableCommands = Helper.loadCommands();
}
}
在上面的示例中,帮助程序类如下所示:
public class Helper {
public static Map<String, Command> loadCommands() {
Map<String, Command> commands = new HashMap<String, Command>();
commands.put("A", new CommandA());
commands.put("B", new CommandB());
commands.put("C", new CommandC());
return commands;
}
}
我的想法是,使用方法在构造函数中设置这样的变量是更好的做法。所以 Base 类看起来像这样:
public class Base {
private final Map<String, Command> availableCommands;
public Base() {
this.setCommands();
}
private void setCommands() {
this.availableCommands = Helper.loadCommands();
}
}
但是现在我无法维护 final 修饰符并出现编译器错误(无法设置最终变量)
另一种方法是:
public class Base {
private final Map<String, Command> availableCommands = new HashMap<String, Command>();
public Base() {
this.setCommands();
}
private void setCommands() {
Helper.loadCommands(availableCommands);
}
}
但在这种情况下,Helper 类中的方法将更改为:
public static void loadCommands(Map<String, Command> commands) {
commands.put("A", new CommandA());
commands.put("B", new CommandB());
commands.put("C", new CommandC());
}
所以不同的是我在哪里创建一个新地图new HashMap<String, Command>();
?我的主要问题是,是否有推荐的方法来执行此操作,因为部分功能来自此 Helper 的静态方法,作为加载带有条目的实际地图的一种方式?
我是在 Base 类还是 Helper 类中创建新地图?在这两种情况下,Helper 将执行实际加载,并且 Base 对包含具体命令的地图的引用将是私有的和最终的。
除了我正在考虑的选项之外,是否还有其他更优雅的方法可以做到这一点?