GoF pattern • Behavioral
GoFBehavioralJava example
Visitor solves a specific structural problem in the design.
Add operations across a structure without changing element classes.
Pattern overview
GoF pattern
Add operations across a structure without changing element classes.
Intent
Represent an operation to perform on the elements of an object structure without changing the element classes.
Problem
A stable structure needs new operations over time, but modifying all element classes for each operation is undesirable.
Solution
Move operations into visitor implementations and dispatch them through accept methods on the structure.
Fit and tradeoffs
FamilyGoF
CategoryBehavioral
Best used when
- When the structure is stable but operations vary.
- When traversing ASTs, rule trees, or document models.
Tradeoffs
- Adding new element types becomes more expensive.
- Double dispatch is harder for some teams to read.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
interface BillingNode {
void accept(BillingVisitor visitor);
}
interface BillingVisitor {
void visit(LineItem lineItem);
void visit(Discount discount);
}
record LineItem(int amount) implements BillingNode {
public void accept(BillingVisitor visitor) { visitor.visit(this); }
}
record Discount(int amount) implements BillingNode {
public void accept(BillingVisitor visitor) { visitor.visit(this); }
}