【发布时间】:2010-12-17 12:01:47
【问题描述】:
有不同的方法可以从构造函数中设置成员变量。我实际上是在讨论如何正确设置最终成员变量,特别是由辅助类加载条目的映射。
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's静态方法,作为使用条目加载实际地图的一种方式?
我是在我的 Base 类还是 Helper 类中创建新地图? 在这两种情况下,Helper 将执行实际加载,并且 Base 对包含具体命令的地图的引用将是私有的和最终的。
除了我正在考虑的选项之外,还有其他更优雅的方法吗?
【问题讨论】:
-
您以这种方式创建的地图是不可变的吗?然后有一个相对不错的选择。
-
好吧,一旦设置好它们就不应该改变。至少不经常
-
我猜地图应该是可变的,否则你会无缘无故地创建不可变地图的多个副本......
-
你不需要把“this”放在你的方法前面。
标签: java constructor final private-members