The Visitor Pattern

archetype Social RolesObject-Oriented Design

Categories: software-engineering

What It Brings

A visitor is someone who arrives from outside. They come to your house, your hospital room, your office — and they bring capabilities the residents lack. A plumber visits to fix the pipes. A doctor visits to examine the patient. The GoF Visitor pattern maps this social transaction onto software: an external object traverses a data structure, performing operations at each node without the nodes needing to know how to perform those operations themselves.

Key structural parallels:

Where It Breaks

Expressions

Origin Story

The Visitor pattern was codified in Design Patterns (1994) by the Gang of Four. It was born from the frustration of needing to add operations to complex object structures (particularly abstract syntax trees in compilers) without modifying the element classes. The social metaphor of visiting was chosen to emphasize that the operation comes from outside the structure — a guest, not a resident. The pattern is notoriously difficult to understand on first encounter, in part because the double-dispatch mechanism doesn’t map cleanly onto the simplicity of the visiting metaphor. It remains one of the most debated GoF patterns, with many developers preferring pattern matching or multimethods where available.

References

Related Mappings