Behavioral

Visitor

Separates algorithms from the objects on which they operate.

AST processingDocument exportReport generation

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

✅ Use when
  • • 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
⚠️ Avoid when
  • • 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

Element.Accept(visitor)
↓ calls
Visitor.VisitElement(element)
↓ implements
PrintVisitor
ExportVisitor
CalcVisitor

How It Works

Elements
Circle
Accept(v)
Rectangle
Accept(v)
Triangle
Accept(v)
Visitor
AreaCalc
VisitCircle()
VisitRectangle()
VisitTriangle()
Different element types
1

Element Structure

Objects with different types in a structure.

1 / 4

Basic Implementation

Area calculator visiting different shapes:

main.go
Loading editor...

Real-World Example: Document Export

Document nodes with HTML and plain text exporters:

main.go
Loading editor...