可以使用这么多新声明吗?

时间:2017-12-05 05:04:17

标签: java-8

我有这个代码来处理我的命令:

public class CommandHandler {

    public static final CommandParser parser = new CommandParser();
    public static HashMap<String, Command> commands = new HashMap<>();

    public static void handleCommand(CommandParser.CommandContainer cmd) {

        if (commands.containsKey(cmd.invoke)) {         
            commands.get(cmd.invoke).action(cmd.event, cmd.args);
            commands.get(cmd.invoke).postAction(cmd.event, cmd.args);
        }
        /* else
            System.err.println("CMD NOT EXIST!"); */
    }
}

public static HashMap<String, Command> commands = new HashMap<>();

private static void addCommands() {
    commands.put(new cmdConfig().getCommand(), new cmdConfig());
    commands.put(new cmdHelp().getCommand(), new cmdHelp());
    commands.put(new cmdPing().getCommand(), new cmdPing());
}

这是一个简短的代码,但我有157个命令。 每个命令都来自具有以下方法的接口:

public interface Command {
    public String getCommand();
    public String help();
    public void action(String[] args);
    public void postAction(String[] args);
}

另外,我也使用此代码:

String input = "random";

if (new cmdPing().getCommand().equals(input)) {
    new cmdPing().help();
}
else if (new cmdConfig().getCommand().equals(input)) {
    new cmdConfig().help();
}
else {
    printError(input + " is not a valid command");
}

我想知道当我使用commands.putif()语句时,是否可以使用许多新语句。

2 个答案:

答案 0 :(得分:2)

你创建一个包含所有命令的HashMap<String, Command> commands,然后不使用该地图来查找命令,这是非常奇怪的,这就是创建这样一个地图的目的。

public static final List<Command> ALL_COMMANDS
    = Collections.unmodifiableList(Arrays.asList(
        new cmdConfig(), new cmdHelp(), new cmdPing(), …
    ));
public static Map<String, Command> ALL_COMMANDS_BY_NAME
    = ALL_COMMANDS.stream()
                  .collect(Collectors.toMap(Command::getCommand, Function.identity()));
String input = "random";
Command cmd = ALL_COMMANDS_BY_NAME.get(input);
if(cmd != null) cmd.help();
else printError(input + " is not a valid command");

如果单个命令的实际实现相当短,您可以考虑在实现enum的单个Command中实现所有这些命令。然后,由于生成的ALL_COMMANDS方法返回所有常量的数组,因此您可以免费获得线性values()列表。其余的应用程序逻辑保持不变。

答案 1 :(得分:1)

删除界面和所有实现类。

相反,使enum成为final commandhelp的{​​{1}}字段,获取帮助的getter和action()方法

不需要为命令名设置getter,因为只有类本身需要使用它。

如果您需要获取给定String的枚举实例,请使用所有枚举所具有的valueOf()方法。