Visitor pattern
In short: The visitor pattern separates an operation from the object structure it works on, so you can add new operations without changing the classes.
In more detail: Each element offers an accept(visitor) method and calls visitor.visit(this) inside it. The visitor holds the matching code per element type (“double dispatch”).
In Depth
- Typical example: A syntax tree of nodes such as number, addition, variable. Visitors are “evaluate”, “print”, “optimise”.
- Advantage: A new operation is a new visitor class, without touching the node classes.
- Disadvantage: New node types force every visitor to change. The pattern pays off when operations change more often than types.
- Alternatives: In languages with pattern matching over sum types (Rust, Kotlin, TypeScript, modern Java) a
matchoften replaces the visitor. - Known from: Compilers, file-system walks,
ast.NodeVisitorin Python.
See also: Iterator pattern