Visitor Pattern: Operations on Object Structures
What you'll learn: How to add new operations to object structures without modifying the objects themselves by using the Visitor pattern.
The Core Problem
Imagine you have a collection of different objects — documents, images, videos — and you need to perform various operations on them: export to PDF, calculate size, generate thumbnails. You could add methods for each operation to each class, but that violates the Single Responsibility Principle and becomes messy when you add new operations.
How Visitor Works
The Visitor pattern separates algorithms from the object structures they operate on. Instead of cramming operations into your classes, you create separate "visitor" objects that traverse your structure and perform operations.
The key mechanism: Each element in your structure accepts a visitor and calls the visitor's appropriate method, passing itself as an argument. This is called "double dispatch" — the operation depends on both the visitor type and the element type.
Real-World Analogy
Think of a health inspector visiting different rooms in a restaurant. The kitchen, dining room, and storage area are the "elements." The inspector is the "visitor" who performs health checks. Each room "accepts" the inspector and lets them perform their specialized inspection. The rooms don't need to know how to inspect themselves — they just need to let the inspector in.
Why Use Visitor?
- Add new operations easily: Create a new visitor class instead of modifying existing element classes
- Keep related operations together: All export logic lives in
ExportVisitor, all size calculation inSizeVisitor - Maintain element stability: Your core object structure remains unchanged
Key Takeaway: The Visitor pattern lets you define new operations on object structures by creating visitor classes that traverse elements, keeping algorithms separate from the objects they operate on.