Visitor
Separates algorithms from the objects on which they operate.
Understanding Visitor
The Visitor pattern separates algorithms from the object structure they operate on, allowing you to add new operations to existing types without modifying them. Each concrete visitor implements a set of Visit methods, one per element type in the structure. In Go, the element types implement an Accept method that calls the appropriate visitor method — this double dispatch ensures the right visitor method is called for each element type. This pattern is commonly used for AST (Abstract Syntax Tree) processing, document export to multiple formats, and generating reports from heterogeneous collections.
Key Concepts
- •Visitor interface — declares Visit methods for each concrete element type in the structure
- •Element interface — declares Accept(visitor) — each concrete element calls the matching Visit method
- •Double dispatch — the combination of Accept() and Visit() ensures correct method resolution for both types
- •Open for operations — new visitors add new operations without touching element code — but adding new elements requires changing all visitors
When to Use
- • You need to perform many unrelated operations on a stable set of types
- • Adding operations is more common than adding new types to the structure
- • You\'re processing ASTs, document trees, or heterogeneous collections
- • You want to accumulate results across a complex object structure
- • The element hierarchy changes frequently — each new type requires updating all visitors
- • A simple type switch achieves the same result with less ceremony in Go
- • The double dispatch pattern is unfamiliar to your team and adds confusion
Structure
How It Works
Element Structure
Objects with different types in a structure.
Basic Implementation
Area calculator visiting different shapes:
Real-World Example: Document Export
Document nodes with HTML and plain text exporters: