4 回答
TA贡献1794条经验 获得超8个赞
对于 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);
TA贡献1828条经验 获得超3个赞
摆脱 switch 的一种可能选择是使用函数的 hashmap:
private String stringMethod(final String action, final String source) {
final Function<String, String> toLowerFunction = String::toLowerCase;
final Function<String, String> toUpperFunction = String::toUpperCase;
final HashMap<String, Function<String, String>> stringFunctions = new HashMap<>();
stringFunctions.put("toLower", toLowerFunction);
stringFunctions.put("toUpper", toUpperFunction);
return stringFunctions.get(action).apply(source);
}
TA贡献1809条经验 获得超8个赞
我不完全确定你想要实现什么。如果你不想继续添加新的
case ("ccc"):
Lmn(b,c,i);
break;
块。
您可以散列 a 中的HashMap<string, method>方法并使用键从映射中获取方法并执行它。
TA贡献1877条经验 获得超1个赞
如果您在同一个变量上有重复的 switch 案例,例如在 methodf和. 然后你可以把事情从里到外:gh
void f(String a) {
switch (a) {
case "aaa": ... ; break;
...
}
}
void g(String a) {
switch (a) {
case "aaa": ... ; break;
case "bbb": ... ; break;
case "ccc": ... ; break;
...
}
}
void h(String a) {
switch (a) {
case "aaa": ... ; break;
...
}
}
可以将面向对象处理为:
class C {
public f() { }
public g() { }
public h() { }
}
class Aaa extends C {
@Override
public f() { test3(b,c); } // Or even just the body of test3
@Override
public g() { }
@Override
public h() { }
}
class Bbb extends C {}
class Ccc extends C {}
然后一旦必须提供特定的 C:
C c;
switch (a) {
case "aaa": c = new Aaa(); break;
case "bbb": c = new Bbb(); break;
case "ccc": c = new Ccc(); break;
...
}
c.f(...);
c.g(...);
c.h(...);
这看起来是间接的,但实际上提高了开发质量。添加新案例并不意味着搜索所有开关案例。
一种情况(“aaa”)的代码都在一个类中,具有自己的专用字段。这可以简化事情并提供更好的概览。
添加回答
举报
