Visitor
Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
The Problem
You have a stable object structure (AST nodes, scene graph objects) and you need to add many unrelated operations over time — type checking, code generation, pretty printing, optimization. Adding each operation as a method to every node class pollutes the classes and requires recompiling the entire hierarchy for each new feature.
Structure
Execution Walkthrough
Element interface
Each Element type declares accept(Visitor&). This is the only method elements need to know about visitors.
Visitor interface
Double dispatch
New operation
Walk structure
Code Comparison
Full C++ Implementation
Participants
Where it is used
Compilers (LLVM/Clang)
AST passes (type checker, const folder, codegen) are Visitors — new passes add no fields to AST nodes.
MDL Compiler
Semantic analysis, AST printer, and code emitter are three Visitors over the same parse tree.
XML/JSON processors
A SAX-style visitor walks the document tree; different visitors extract, validate, or transform.
Game engines
Scene graph Visitor computes bounding boxes, renders, or serializes without touching entity classes.