Visitor
Lets you add new operations to an object structure without modifying the objects themselves, by separating the algorithm from the object structure it operates on.
errorWhat Problem Does the Visitor Pattern Solve?
When you need to perform many distinct, unrelated operations on a stable object hierarchy, adding each operation directly to every class pollutes those classes with logic that isn't their core responsibility. The hierarchy must be recompiled for every new operation, violating the Open/Closed Principle.
check_circleHow the Visitor Pattern Works
Declare a Visitor interface with a visit method for each concrete element type in the hierarchy. Each element implements an accept method that calls the appropriate visit method on the visitor, passing itself. New operations are implemented as new Visitor classes without touching the element hierarchy at all.
Visitor Pattern Architecture
Rendering diagram...
Implementation by Language
Visitor Pattern in the Real World
“Think of a tax auditor visiting different types of businesses—a restaurant, a law firm, a retail shop. The auditor (visitor) knows exactly what to examine at each type of business and applies the appropriate inspection procedure. The businesses (elements) simply let the auditor in; they don't change their own operations to accommodate the audit.”
Frequently Asked Questions
helpWhy is the Visitor pattern considered difficult to use?
Visitor requires double dispatch — the element calls visitor.visit(this), passing itself. This is unintuitive and creates tight coupling between the visitor and all element types. Adding a new element type forces changes to every visitor. The pattern trades element extensibility for operation extensibility.
helpWhat are modern alternatives to the Visitor pattern?
Pattern matching (available in Rust, Scala, and proposed for JavaScript) handles the same use case more ergonomically. In TypeScript, discriminated unions with switch statements achieve similar results. Use Visitor only when you need to add operations frequently but element types are stable.