10 Visitor (Behavioral) Design Pattern

The Visitor Design Pattern is a behavioral design pattern that allows you to add new operations to classes of objects without modifying their structure. Instead, the new behavior is implemented in a separate object, called a visitor, that is passed to the objects it needs to operate on.

Intent

  • Separate an algorithm from the objects on which it operates.
  • Add new operations to existing object structures without altering the classes.
  • Simplify extending operations without polluting the existing class hierarchy.

Key Components

  1. Visitor Interface:
    • Declares operations to be performed on elements of an object structure. One method per concrete element class.
  2. Concrete Visitors:
    • Implement the visitor interface and define specific behaviors for each type of element.
  3. Element Interface:
    • Declares a method for accepting a visitor. This method typically takes a visitor as an argument.
  4. Concrete Elements:
    • Implement the element interface and provide the accept method that calls the appropriate method on the visitor.
  5. Object Structure:
    • A collection or hierarchy of elements that can accept visitors.

When to Use

  • When you need to perform many unrelated operations on an object structure.
  • When extending object structures is easier than modifying them.
  • To maintain the Open/Closed Principle: You can add new behaviors without changing existing classes.