Codacoda
Back to Academy

design patterns

Visitor

The Visitor pattern lets you define a new operation without changing the classes of the elements on which it operates. It separates an algorithm from the object structure it operates on by moving the operation into a separate visitor object. The key participants are the Visitor (declares a visit operation for each ConcreteElement class), ConcreteVisitor (implements each operation declared by Visitor), Element (defines an accept method that takes a visitor), and ConcreteElement (implements the accept method by calling the visitor's corresponding visit method). Think of a tax inspector visiting different types of businesses: the inspector (visitor) applies different rules to restaurants, shops, and factories (elements) without those businesses needing to know about tax law. Use Visitor when you need to perform many distinct and unrelated operations on objects in an object structure and you want to avoid polluting their classes with these operations.

Use Cases

  • Compilers applying operations to AST nodes (type checking, code gen)
  • Exporting data structures to multiple formats (JSON, XML, HTML)
  • Calculating different metrics on document elements
  • Applying operations across heterogeneous object collections

Visualization

accept(v) → v.visitA(this)<<interface>>Visitor+visitA(elemA)+visitB(elemB)ConcreteVisitor+visitA()+visitB()<<interface>>Element+accept(visitor)ElementA+accept(visitor)+opA()ElementB+accept(visitor)+opB()
Speed:1x
Visitor — adds new operations to object structures without modifying the elementsStep 1 / 7

Implementation

Output

Click "Run Code" to see output...