ASTNode的accept()方法是什么,它如何使用ASTVisitor?

5
< p >ASTNode 的 < code >accept 方法是做什么用的(javadoc 没有提供太多帮助...)?什么时候会调用 < code >visit(Expression node) 方法呢?下面是一个需要使用它的示例代码:
final List<Expression> listi = new ArrayList<Expression>();
String stringi = opi.generate(entryContract, true_false_maybe);
// stringi representes an expression, for example "g!=h".
parser.setSource(stringi.toCharArray());
unit = (CompilationUnit) parser.createAST(null); 
ASTNode astRoot = unit.getRoot();
astRoot.accept(new ASTVisitor() {
 public boolean visit(Expression node) {
  listi.add(node);
  return true;
 }
});

Thank you

1个回答

2
我猜你的 `Expression` 类是 `ASTNode` 类的子类型,而 `ASTVisitor` 类则提供其他访问方法(这些方法肯定为空),接受其他 `ASTNode` 子类作为参数。
这是 GoF 访问者设计模式 的一种实现方式(也在 维基百科 上有描述)。
`ASTNode` 上的 `accept` 方法只会调用访问者实现上的 `visit` 方法,并将自身作为参数传递给 `visit` 方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接