Design Patterns Visitor
The Visitor pattern separates an operation from the objects it works on. A visitor object travels across a structure and performs its task on each element. New operations arrive as new visitor classes, and the element classes stay untouched.
The Real-World Analogy
A city inspector visits different buildings: a school, a shop, and a factory. Each building welcomes the inspector, and the inspector applies rules suited to that building type. A fire inspector and a tax inspector can follow the same route with different checklists, and no building needs reconstruction.
Problem Without Visitor
Shapes: Circle, Rectangle, Triangle Need: area(), perimeter(), exportToXml(), draw() ... Each new operation → edit every shape class Shape classes bloat with unrelated tasks
Solution With Visitor
Elements Visitors ┌───────────┐ accept(v) ┌──────────────────┐ │ Circle │ ─────────────────▶ │ AreaVisitor │ │ Rectangle │ v.visit(this) │ XmlExportVisitor │ │ Triangle │ │ DrawVisitor │ └───────────┘ └──────────────────┘ New task → one new visitor class. Shapes stay unchanged.
Double Dispatch
Visitor relies on a trick called double dispatch. The element receives the visitor through accept(). Inside accept(), it calls the visitor method matching its own type. Two calls together pick the exact code to run.
shape.accept(areaVisitor)
│
▼
Circle.accept(v) { v.visitCircle(this); }
│
▼
AreaVisitor.visitCircle(circle) → π × r × r
Structure
┌────────────────────┐ ┌─────────────────────────┐
│ «interface» │ │ «interface» Visitor │
│ Shape │ accepts │ + visitCircle(Circle) │
│ + accept(Visitor) │ ───────▶ │ + visitRect(Rectangle) │
└─────────▲──────────┘ └────────────▲────────────┘
┌────┴─────┐ ┌─────────┴────────┐
Circle Rectangle AreaVisitor PerimeterVisitor
Code Example
interface Shape { void accept(Visitor v); }
class Circle implements Shape {
double radius;
public void accept(Visitor v) { v.visitCircle(this); }
}
class Rectangle implements Shape {
double width, height;
public void accept(Visitor v) { v.visitRectangle(this); }
}
interface Visitor {
void visitCircle(Circle c);
void visitRectangle(Rectangle r);
}
class AreaVisitor implements Visitor {
double total = 0;
public void visitCircle(Circle c) { total += 3.14 * c.radius * c.radius; }
public void visitRectangle(Rectangle r) { total += r.width * r.height; }
}
List shapes = List.of(new Circle(2), new Rectangle(3, 4));
AreaVisitor area = new AreaVisitor();
for (Shape s : shapes) {
s.accept(area);
}
print(area.total);Trade-Off With Element Changes
Visitor makes new operations cheap and new element types expensive. A new Shape class forces an update to every visitor. Choose Visitor when the element family stays stable and the operations keep growing.
Real Projects Using Visitor
| Scenario | Visitors |
|---|---|
| Compilers | Type checker, code generator, optimizer |
| Document trees | Word counter, exporter, spell checker |
| Shopping carts | Tax calculator, shipping estimator |
| File systems | Size counter, search, backup |
Advantages and Disadvantages
| Advantages | Disadvantages |
|---|---|
| New operations without editing elements | New element types break all visitors |
| Related logic gathers in one class | Visitors need access to element details |
| Works well with Composite trees | Double dispatch confuses beginners |
Step-by-Step Walkthrough
Trace the loop at the bottom of the code example. The first shape is a Circle with radius 2. Calling s.accept(area) enters Circle.accept(), which calls visitCircle(this). AreaVisitor adds 3.14 × 2 × 2 to its running total. Rectangle follows the same path and adds 3 × 4.
A PerimeterVisitor needs one new class. The Circle and Rectangle classes stay untouched.
Visitor With Composite Trees
Folders contain files and other folders. A visitor passes through the tree and handles each node type. One visitor adds file sizes, and another collects matching names. Both reuse the same traversal and keep the folder classes clean.
Common Mistakes
- Choosing Visitor when new element types arrive every month. Each new type forces edits to every visitor.
- Exposing private fields only to satisfy visitors, which weakens encapsulation.
- Mixing unrelated work in one visitor. Keep each visitor focused on one task.
Plain-Words Summary
Visitor feels abstract until a real need appears. Imagine a document tree that needs word counts today, an export tomorrow, and a spell check next month. Adding each task to every node class would bury them in unrelated code. A visitor per task keeps nodes tidy and gathers each feature in one file that a teammate can open and understand.
Key Takeaways
- A visitor adds operations to a family of classes without changing them.
- Double dispatch routes each element to the matching visitor method.
- Stable element sets and growing operation lists suit this pattern.
- Visitor pairs naturally with Composite structures.
