Tutorials Design Patterns Mastery

Visitor Pattern: Separating operations from data structures

On this page

The Visitor Pattern

The Visitor Pattern is used to separate an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures themselves.

1. Scenario: Document Export

You have a Document class containing Paragraph and Image nodes. Now you want to add Export to PDF and Export to HTML. Instead of putting ToPdf() methods inside Paragraph and Image classes, you create a Visitor.

public interface IVisitor 
{
    void Visit(Paragraph p);
    void Visit(Image i);
}

public class PdfVisitor : IVisitor { ... }

2. Double Dispatch

The Visitor pattern uses a technique called Double Dispatch: the element calls visitor.Visit(this). This allows the visitor to know the *exact runtime type* of the object it is dealing with, even when processing a generic list of base components.

4. Interview Mastery

Q: "Why is the Visitor pattern often criticized as an anti-pattern?"

Architect Answer: "Because it is **Inflexible for Data Changes**. If you add a new element type (e.g., `Table`), you MUST update the `IVisitor` interface and EVERY single concrete visitor class in the system. It breaks the Open/Closed Principle for data. You should ONLY use Visitor when your object structure is **Fixed** (rarely changes) but you expect to add many new **Operations** over time."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details