How to avoid many 'if's' and provide runtime params on execution

拈花ヽ惹草 提交于 2019-12-24 14:28:40

问题


I am trying to avoid lots of if's and use an OOP way to execute different executions. the execution is determined by ACTION integer which I get from an API on runtime.

I though about command pattern and this is how it looks:

I created on Spring configuration a hashmap:

      @Bean
        public HashMap<Integer, Command> hashmapCommands() {
            HashMap<Integer, Command> supportedCommands = new HashMap<>();
            supportedCommands.put(command.action.getId(), myCommand());
            ..
    }

  @Bean
    public Command MyCommand() {
        return new myCommand();
    }


public class MyCommand implements Command {

    public final static ACTION action = 1;
   @Override
    public void execute(String runTimeData) {
      //doSomeLogic
    }

}

Now on some other place on my case I am injecting hashmapCommands:

on inoker class:

public class TestCommands(){
..
 supportedCommands = (HashMap<Integer, Command>) context.getBean("hashmapCommands");
...

public void someTest(){
 Command myCommand = supportedCommands.get(1);
 reportCommandBase.execute("some runtimeMessage");
}

I have params inside execution() it's wrong to use that using Command pattern.

As you can see I must send runtime message and avoiding if statements which retrieve the command execution from hashmap. But i need to sent param which I am getting only on runtime.

Mybe i am forcing Command pattern on my case? other suggestions ?

来源:https://stackoverflow.com/questions/36194878/how-to-avoid-many-ifs-and-provide-runtime-params-on-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!