0
0
LldConceptBeginner · 3 min read

Visitor Pattern: Definition, Example, and When to Use

The Visitor Pattern is a design pattern that lets you add new operations to objects without changing their classes. It separates an algorithm from the objects it works on by letting a visitor object perform actions on elements of an object structure.
⚙️

How It Works

Imagine you have a group of different objects, like shapes: circles, squares, and triangles. You want to perform different actions on them, like drawing or calculating area, but you don't want to change the shape classes every time you add a new action.

The Visitor Pattern solves this by letting you create a separate visitor object that "visits" each shape and performs the action. Each shape accepts the visitor and calls the right method for itself. This way, you can add new operations easily without touching the shape classes.

Think of it like a museum guide (visitor) who visits different exhibits (objects) and explains something unique about each one without changing the exhibits themselves.

💻

Example

This example shows shapes accepting a visitor that calculates their area.

python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def accept(self, visitor):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def accept(self, visitor):
        return visitor.visit_circle(self)

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def accept(self, visitor):
        return visitor.visit_square(self)

class Visitor(ABC):
    @abstractmethod
    def visit_circle(self, circle):
        pass

    @abstractmethod
    def visit_square(self, square):
        pass

class AreaCalculator(Visitor):
    def visit_circle(self, circle):
        return 3.14 * circle.radius * circle.radius

    def visit_square(self, square):
        return square.side * square.side

shapes = [Circle(5), Square(4)]
calculator = AreaCalculator()

for shape in shapes:
    area = shape.accept(calculator)
    print(f"Area: {area}")
Output
Area: 78.5 Area: 16
🎯

When to Use

Use the Visitor Pattern when you have a complex object structure and want to add new operations without changing the objects. It is helpful when you expect to add many unrelated operations over time.

For example, in a graphics editor, you might want to add operations like exporting, printing, or calculating statistics on shapes without modifying the shape classes. The visitor lets you keep these operations separate and organized.

Key Points

  • The Visitor Pattern separates operations from object structures.
  • It allows adding new operations without changing existing classes.
  • Each object accepts a visitor that performs the operation.
  • Good for stable object structures but changing operations.

Key Takeaways

Visitor Pattern lets you add new operations without changing object classes.
Objects accept a visitor that performs the operation specific to their type.
It is useful when object structures are stable but operations change often.
Helps keep code organized by separating algorithms from objects.
Best used when you need many unrelated operations on the same objects.