Java Design Patterns Tutorial - Java Design Pattern - Visitor Pattern








In visitor pattern, element object accepts the visitor object and visitor object handles the operation on the element object.

This pattern is a behavior pattern.

By this way, execution algorithm of element can be changed from different visitors.

Example

class TreeNode {/*from   ww  w  .  j a  va  2s .c o m*/
  private String name;
  public TreeNode(String name) {
    this.name = name;
  }
  public String getName() {
    return name;
  }
  public void accept(NodeVisitor v) {
    v.visit(this);
  }
}
interface NodeVisitor {
  public void visit(TreeNode n);
}
class ConsoleVisitor implements NodeVisitor {
  @Override
  public void visit(TreeNode n) {
    System.out.println("console:" + n.getName());
  }
}

class EmailVisitor implements NodeVisitor {
  @Override
  public void visit(TreeNode n) {
    System.out.println("email:" + n.getName());
  }
}

public class Main {
  public static void main(String[] args) {

    TreeNode computer = new TreeNode("Java2s.com");
    computer.accept(new ConsoleVisitor());
    computer.accept(new EmailVisitor());
  }
}

The code above generates the following result.