I am in the process of refactoring a Java application that accepts commands from terminal. Currently, there is a huge if-else structure that checks for the command issued and executes the required method. I was wondering if it was possible to replace this logic with a well established design pattern. I looked at Command pattern and Strategy pattern, but cannot seem to get my head around it in this scenario. Please suggest.
Update: I do use JCommander, but that doesn't get rid of the if-else structure.
MyCommand cmd1 = new MyCommand();
...
...
MyCommandN cmdN = new MyCommandN();
JCommander cmd = new JCommander();
cmd.addCommand("myCommand1", cmd1);
...
...
cmd.addCommand("myCommandN", cmdN);
try {
cmd.parse(args);
//
if ("myCommand1".equals(cmd.getParsedCommand())) {
System.out.println("running command1");
}
...
...
else if ("myCommandN".equals(cmd.getParsedCommand())) {
// Sysout statements only for illustration. I call command specific methods here.
System.out.println("running commandN");
} else {
cmd.usage();
}
//
} catch (ParameterException ex) {
System.out.println(ex.getMessage());
cmd.usage();
}