Search code examples
javadesign-patternsreflectioncommand-pattern

Command pattern vs reflection


I have controller that executes some commands according to command name, taken from url. The main point is in not to use if and switch clauses. As I know there are ONLY two ways how to do it - 1) command pattern 2) reflection.

//Command pattern
class Controller{
  private HashMap<String,Command> commands;
  public void executeCommand(String commandName){
    commands.get(commandName).execute();
  }
  ...
}

//reflection
class Controller{
  public void readCommand(){
    ....
  }
  public void executeCommand(String commandName){
    this.getClass().getMethod(commandName+"Command").invoke(this);
  }
  ...
}

So the questios:

  1. Which one is better?
  2. Is it normal in one application to let developers use one of the methods they want.
  3. Are there other ways?

Solution

    1. first way is better, use reflections only when don't have other options.
    2. in one application there should be one approach to solve one kind of problem.
    3. I think the first approach is fine. (much better then if/else blocks)