Visitor Idea

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

The Visitor pattern separates structure traversal from operations: elements call accept(visitor), and the visitor defines visit methods for each node type.

Useful when many operations are performed on stable structures (such as compiler ASTs, document trees).

Separate operation from structure: ElementVisitor [1].

Where used

Compiler frontends, serialization over ASTs, operations on stable object graphs without needing to open node types constantly.

Depth

The Visitor pattern encapsulates operations in visitor classes, while elements of a heterogeneous structure provide an accept method. By calling visitor.visit(this), both the concrete visitor type and the concrete element type are taken into account in method selection.

New operations can be added without having to fill each element class with additional domain logic. However, new element types are costly since all existing visitor interfaces and implementations need to be extended. Therefore, the pattern fits stable element hierarchies with varying evaluations.

Difficulty levels

  1. Track accept and visit in a small class model.
  2. Explain double dispatch compared to simple overriding.
  3. Compare extension costs for new operations and new elements.

Pitfalls

A visitor is not just a collection of instanceof checks. If such case distinctions are maintained centrally, type safety and the actual dispatch advantage are lost.


Sources

University approvals: 0
Tasks
Question 1

What does the Visitor pattern decouple?

Question 2

For which development is the Visitor pattern particularly suitable?

Question 3

Implement accept in Num and Add. EvalVisitor should evaluate expressions made up of numbers and additions.

Hint

Each accept method calls the appropriate overloaded visit method. Fields of the visited objects are accessible through the parameter.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy