separate data structure from algorithms run on the data structure - perform new operations on nodes of an AST without modifying the node classes themselves

basic

  • Used with abstract syntax tree (AST) in compilers
  • relies on double dispatch
    • AST node interface has common accept(visitor)
    • each concrete node class implements it, and calls visitor.visit(this)
    • Visitor interface defines visit() for every concrete AST node type in tree
    • concrete visitors define specific algorithm for each node type
      • a visitor could calculate the area
      • another could export tree to a different format

benefits

  • separation of concerns - AST node focuses on structure and traversal, while visitor handles operations
  • visitors can be added without modifying the AST node class
  • all logic for a single pass (like type checking) is contained in one visitor class
  • no messy type checking