java - 替换 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 语句。
我对示例进行了一些更新,以使其更有意义。一些方法调用不需要使用所有参数。
解决方案
对于 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);
推荐阅读
- listview - 如何滚动嵌套在 Flutter 中的 Listview
- c# - .Net 解析 ConfigurationSection 抛出异常
- rust - Struct 中的 HashMap 错误:不能将“&”引用中的数据作为可变借用
- sql - 如果 SQL 中的列值为空,如何用另一行更新一行
- visual-studio - .NET4.7.2“PackageReference”项目中的 Razor Intellisense?
- c# - 如何修复“System.InvalidOperationException”
- objective-c - 如何将完成视图控制器代码从 objc 转换为 swift
- c++ - 旋转后更新 AVL 树中的平衡因子 - 我做错了什么?
- python - Django:如何通过表单提交当前用户的用户名而无需用户输入
- c# - Unity 中的嵌套类有一些问题