design patterns ·

Visitor

Lets you add new operations to existing object structures without modifying the classes of those objects.

hard2hgeneraljava
Ask GPTConfidence

Theory

Explanation

Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.

When you have a stable set of element classes but frequently need to add new operations on them, Visitor lets you add the operations externally without touching the element classes.

Element classes implement accept(Visitor). They call visitor.visit(this) - passing themselves to the visitor. The Visitor has an overloaded visit() method for each Element type, implementing the specific operation.

When to use

AST traversal in compilers, document export (HTML/PDF/XML from the same DOM), tax calculation over product types, static analysis tools, report generation over heterogeneous collections.

When not to

When the element class hierarchy frequently changes - Visitor requires updating all visitors for each new element. When the operations are simple - direct methods on elements are clearer.

Key insights

  • Double dispatch: first dispatch on element type (accept), second dispatch on visitor type (visit)
  • Visitor works best when the element hierarchy is stable but operations change frequently
  • The element hierarchy stability constraint is the key trade-off vs extending element classes directly
  • Java compiler's AST traversal uses Visitor extensively