Is there any advantage for using visitor pattern in a recursive scenario? If so can you demonstrate it programmatically?
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);
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With