我一直想知道是否有办法替换当前的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我很好奇是否有更好的方法而不是像上面的场景那样使用 switch 语句。
我对示例进行了一些更新,使其更有意义。某些方法调用不需要使用所有参数。
对于Java 7及以下版本,我们可以声明一个接口来实现函数。
对于 Java 8+,我们可以使用Function接口。
界面:
public interface FunctionExecutor {
public Object execute(String from,String to);
}
Run Code Online (Sandbox Code Playgroud)
函数上下文:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
功能实现:
public class RunFunctionImpl implements FunctionExecutor{
@Override
public Object execute(String from, String to) {
System.out.println("function run");
return null;
}
}
// OTHER FUCNTIONS
Run Code Online (Sandbox Code Playgroud)
寄存器功能:
FunctionContect contex = new FunctionContect();
contex.register("run", new RunFunctionImpl());
contex.register("walk", new WalkFunctionImpl());
contex.register("hide", new HideFunctionImpl());
Run Code Online (Sandbox Code Playgroud)
通话功能
context.call(action, from, to);
Run Code Online (Sandbox Code Playgroud)
或者
context.get(action).execute(from,to);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7126 次 |
| 最近记录: |