Course contentsShow
← Computer Science
Lesson 2299 of 2,87251. Design PatternsFree lesson

Visitor Pattern

Separating algorithms from object structures by defining new operations without changing the classes.

Visitor Pattern

What you'll learn: How to add new operations to existing object structures without modifying the classes themselves.

The Core Problem

Imagine you have a stable hierarchy of classes (like shapes, documents, or nodes in a tree) that rarely changes. Now you need to perform various operations on these objects—print them, serialize them, calculate metrics, export to different formats. Adding each new operation means modifying every class in the hierarchy. That's messy and violates the open-closed principle.

How Visitor Works

The Visitor pattern separates algorithms from the objects they operate on. Instead of putting operations inside your classes, you create separate "visitor" objects that visit each element in your structure.

The analogy: Think of health inspectors visiting different types of restaurants (fast food, fine dining, cafés). Each restaurant type is stable, but new types of inspections can be added (health, fire safety, accessibility) without modifying the restaurant classes themselves. Each inspector knows how to inspect each restaurant type.

The Mechanism

Your element classes define an accept(visitor) method that takes a visitor. Inside accept, the element calls the visitor's appropriate method, passing itself: visitor.visit(this). The visitor has multiple overloaded visit() methods—one for each element type.

This double dispatch technique lets you add new operations by creating new visitor classes without touching the element classes.

When to Use It

  • Your object structure is stable but operations change frequently
  • You need to perform unrelated operations across a hierarchy
  • You want to avoid polluting classes with many unrelated methods

Key Takeaway: The Visitor pattern lets you define new operations on a stable object structure by moving the operation logic into separate visitor classes, achieving extensibility through composition rather than modification.