动态初始化对象

托尼

以下代码是简化版本。WriteRead是实现了类IAction接口。

IAction newAction;
if (userInput.equalsIgnoreCase("WRITE")){
    newAction = new Write();
}
else if (userInput.equalsIgnoreCase("READ")){
    newAction = new Read();
}
...

如果我要执行许多动作,那么我将不得不执行过多的if语句。因此,问题是是否存在一种无需遍历所有这些if语句即可自动创建每个类的方法?

杰斯珀

我取决于您所说的“自动”。计算机会自动执行操作,但不会在有人编程自动执行操作之前执行。您的意思可能是“不太麻烦”。这是一种使用Java 8功能的方法。

// Make a Map that tells what word should be coupled to what action
Map<String, Supplier<IAction>> actionMapping = new HashMap<>();
actionMapping.put("WRITE", Write::new);
actionMapping.put("READ", Read::new);

// When you get user input, simply lookup the supplier
// in the map and call get() on it
IAction action = actionMapping.get(userInput.toUpperCase()).get();

如果您未使用Java 8,则可以使用略有不同(但类似)的方法:

// Map that tells what word should be coupled to what action
Map<String, Class<? extends IAction>> actionMapping = new HashMap<>();
actionMapping.put("WRITE", Write.class);
actionMapping.put("READ", Read.class);

// Lookup the action class for the input and instantiate it
IAction action = actionMapping.get(userInput.toUpperCase()).newInstance();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章