Listener模式
使用ParseTreeWalker遍歷樹的過程中(深度優先),每次進入和退出規則節點時,觸發對應的enterRule/exitRule方法。
使用示例
//step1:創建ParseTreeWalker
ParseTreeWalker walker = new ParseTreeWalker();
//step2:創建ParseTreeListener和ParseTree
ParseTreeListener listener = ...,
ParseTree tree = ...;
//step3:遍歷樹
walker.walk(listener, tree);
原理解析
Visitor模式
使用示例
//step1:創建visitor和tree
XXXParserVisitor visitor = ...;
ParseTree tree = ...;
//step2:遍歷樹
visitor.visit(tree);
原理解析
public T visit(ParseTree tree) {
return tree.accept(this);
}
public T visitChildren(RuleNode node) {
T result = this.defaultResult();
int n = node.getChildCount();
for(int i = 0; i < n && this.shouldVisitNextChild(node, result); ++i) {
ParseTree c = node.getChild(i);
T childResult = c.accept(this);
result = this.aggregateResult(result, childResult);
}
return result;
}
參考: