我正在编写一个程序,用户可以在其中输入类似的内容
add 5 2
或
define foo
现在我知道处理此输入的唯一方法是一堆 if/else if 语句,即
if(args[0] == "add") add();
else if (args[0] == "define") define();
else print("Command not found.");
是否有更好的方法来做到这一点,或者可能是这些类型输入的标准数据结构/算法?我专门使用 Java,但如果可能的话,我更喜欢与语言无关的答案。谢谢!
最佳答案
设计模式命令可用于此目标。例如:
abstract class Command {
abstract public String getCommandName();
abstract public String doAction();
}
要定义自己的函数,只需实现 Command
类:
class AddCommand extends Command {
@Override
public String getCommandName() {
return "add";
}
@Override
public String doAction() {
// do your action
}
}
那么你的主类应该是这样的:
public class Main {
private static Map<String, Command> commands = new HashMap<String, Command>();
private static void init() {
Command addCommand = new AddCommand();
commands.put(addCommand.getCommandName(), addCommand);
}
public static void main (String[] args) {
init();
if (args[0] != null) {
Command command = commands.get(args[0]);
if (command != null) {
System.out.println(command.doAction());
} else {
System.out.println("Command not found");
}
}
}
关于java - 我应该如何解析命令行样式输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16511871/