# Purpose
The Visitor pattern lets you add new operations to an object structure without changing the classes of the elements on which it operates.
# Problem
Difficulty adding new operations or behaviors to complex object structures without having to modify each of its constituent classes.
# Solution
Externalize the operations into a "Visitor" object. The original classes accept the visitor and delegate execution to it, keeping the base classes clean and focused.
# Structure
# Participants
- Visitor (Interface): Defines visits for each concrete element.
- ConcreteVisitor: Implements the specific logic of the operation.
- Element (Interface): Defines the accept() method.
- ConcreteElement: The object being visited.
# When to Use It
In systems with stable data structures but where the operations on them change or grow frequently.
# Advantages
-
verified
Flexibility: New operations without touching old code.
-
verified
Cohesion: Groups related operations in one place.
# Disadvantages
-
warning
Coupling: Visitors are heavily tied to the element hierarchy.
-
warning
Encapsulation: Often requires exposing private fields to work.
# Example: Accounting
Generating different types of financial reports (Visitor) by iterating over the list of accounts (Elements).
# Java Code
interface Account { void accept(Visitor v); }
class SavingsAccount implements Account {
double balance;
public void accept(Visitor v) { v.visit(this); }
}
class ReportVisitor implements Visitor {
double total = 0;
public void visit(SavingsAccount s) { total += s.balance; }
}
# Mapping Participants
- Account: Element.
- AccountVisitor: Visitor Interface.
- SavingsAccount/LoanAccount: ConcreteElements.
- FinancialReportVisitor: ConcreteVisitor.
# Conclusions
Powerful solution for data-driven architectures where a wide variety of external analytics or operations on stable objects are needed.
# Related Patterns
Composite
Visitor can traverse hierarchical structures of type Composite.
Interpreter
It is often used to traverse the syntax tree and interpret the language.