gpt4 book ai didi

java - 替换 Java 的 switch 语句

转载 作者:行者123 更新时间:2023-11-30 01:54:29 24 4
gpt4 key购买 nike

我一直想知道是否有办法替换当前的 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 语句。

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

最佳答案

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

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

界面:

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);

关于java - 替换 Java 的 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54940583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com