有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何避免许多“if”并在执行时提供运行时参数

我试图避免大量的if's,并使用OOP方式执行不同的执行。执行由我在运行时从API获取的操作整数决定

我想到了命令模式,它看起来是这样的:

我在Spring配置上创建了一个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
    }

}

现在,在我的案例的其他地方,我正在注入hashmapCommands:

在inoker类上:

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

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

我在execution()中有参数使用命令模式是错误的

正如您所看到的,我必须发送运行时消息并避免使用从hashmap检索命令执行的if语句。但是我需要发送param,我只在运行时得到它

Mybe我在我的案子上强制执行命令模式?其他建议


共 (0) 个答案