使用Lambda表达式来减少访问者模式的代码混淆。
考虑以下Antlr4生成的代码:
public class MyVisitor extends SomeBaseVisitor {
@Override
public String visitSomeRule(SomeRuleContext ctx) {
String result = "";
// Some code here...
return result;
}
@Override
public String visitAnotherRule(AnotherRuleContext ctx) {
String result = "";
// Some code here...
return result;
}
}
使用Java 8中的Lambda表达式,可以将访问者模式的代码重写为:
public class MyVisitor extends SomeBaseVisitor {
private Map, Function> visitors = new HashMap<>();
public MyVisitor() {
visitors.put(SomeRuleContext.class, this::visitSomeRule);
visitors.put(AnotherRuleContext.class, this::visitAnotherRule);
}
@Override
public String visit(ParserRuleContext ctx) {
return visitors.get(ctx.getClass()).apply(ctx);
}
private String visitSomeRule(SomeRuleContext ctx) {
String result = "";
// Some code here...
return result;
}
private String visitAnotherRule(AnotherRuleContext ctx) {
String result = "";
// Some code here...
return result;
}
}
此重构允许我们将访问者方法存储在Map中并根据上下文类动态调用它们,在代码量大大减少的情况下仍保持代码清晰易读。