首页 > 解决方案 > 替换 switch 语句 Java

问题描述

我一直想知道是否有办法替换我拥有的当前 switch 语句。下面是我拥有的代码示例,尽管我拥有的语句要长得多,而且只会变得更大。switch 方法通过文件读取器调用,因此它读取一行,然后调用此函数并分配值。

public static void example(String action, String from, String to){
 switch (action) {
           case ("run"):
                runTo(from,to);
                break;
           case ("walk"):
                walkTo(from,to);
                break;
           case ("hide"):
                hideAt(to);
                break;
            }
 }

编辑:我很好奇是否有更好的方法来代替使用上述场景的 switch 语句。

我对示例进行了一些更新,以使其更有意义。一些方法调用不需要使用所有参数。

标签: javaswitch-statement

解决方案


对于 Java 7 及以下版本,我们可以为函数实现声明一个接口。

对于 Java 8+,我们可以使用Function接口。

界面:

public interface FunctionExecutor {
    public Object execute(String from,String to);

}

函数上下文:

public class FunctionContect {
   HashMap<String, FunctionExecutor> context=new HashMap<String, FunctionExecutor>();

    public void register(String name,FunctionExecutor function){
        context.put(name, function);
    }

   public Object call(String name,String from,String to){
      return    context.get(name).execute(from, to);
   }

   public FunctionExecutor get(String name){
      return context.get(name);
   }

  }

功能实现:

public class RunFunctionImpl implements FunctionExecutor{

    @Override
    public Object execute(String from, String to) {
       System.out.println("function run");
        return null;
   }

}

// OTHER FUCNTIONS

注册功能:

    FunctionContect contex = new FunctionContect();
    contex.register("run", new RunFunctionImpl());
    contex.register("walk", new WalkFunctionImpl());
    contex.register("hide", new HideFunctionImpl());

调用函数

 context.call(action, from, to);

或者

 context.get(action).execute(from,to);

推荐阅读