views:

210

answers:

2

Is there any advantage for using visitor pattern in a recursive scenario? If so can you demonstrate it programmatically?

A: 

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.

theG
+1  A: 

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);
    }
  }
}
Steve B.