My situation is as follows.
I have an abstract Command
class which has an exec
method. I have a series of concrete command classes that extend this abstract class.
I have a CommandFactory
in the context class that creates and returns an appropriate command based on cmdline args which I parsed and sent to the factory. (no problems here, I'm able to parse cmdline args just fine).
However within the command factory I have this large list of if-else-if not unlike this
public Command getCmd(String cmdType){
if(cmdType == null){
return null;
}
if(cmdType.equalsIgnoreCase("CLEAN")){
return new CleanCmd();
} else if(cmdType.equalsIgnoreCase("KILL")){
return new KillCmd();
} else if(cmdType.equalsIgnoreCase("START")){
return new StartCmd();
}
return null;
}
Note: The input args are a set of flags and args which are too complex for the scope of this question. You can just think of the equalsIgnoreCase as something more complex.
However I think this if else construct is kinda ugly. I'd like to replace it with something more elegant. Also correct me if I am wrong the current paradigm also violates the open-close principle because every time I add a new command I modify the factory ?