Java visitor pattern

In the visitor pattern, an element object accepts a visitor object, and the visitor object handles operations on the element object.

This pattern is a behavioral pattern.

In this way, it is possible to change the execution algorithm of an element from different visitors.

example

class TreeNode {
  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("voidme.com");
    computer.accept(new ConsoleVisitor());
    computer.accept(new EmailVisitor());
  }
}

The above code produces the following result.

console:voidme.com

email:voidme.com

Guess you like

Origin blog.csdn.net/unbelievevc/article/details/131844010