Visitor pattern and recursion
-
06-09-2019 - |
Question
Is there any advantage for using visitor pattern in a recursive scenario? If so can you demonstrate it programmatically?
Solution
How about traversing a binary tree? e.g.
private class NodeVisitor{
public void visit(VisitableNode<T> node){
if (node!=null) {
print node.data;
}
}
}
public class VisitableTree<T> {
private VisitableNode<T> root;
public void printNodes(){
new NodeVisitor.visit(root);
}
private class VisitableNode<T> {
T data;
VisitableNode<T> left;
VisitableNode<T> right;
public void visit(NodeVisitor<T> visitor){
..do something
visitor.visit(left);
visitor.visit(right);
}
}
}
OTHER TIPS
I think the main benefit is that it only requires iterations over collections 1 level deep. It can call back, but at least the accept() method will be clean.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow