Design Pattern | Visitor Pattern

What Is the Visitor Pattern?

  • Visitor means visitor.
  • The Visitor pattern separates data structures from processing.
  • It prepares visitor classes that traverse a data structure and leaves processing to those visitor classes. When you want to add new processing, you create a new visitor. The data structure only needs to accept the visitor.
  • In GoF design patterns, it is classified as a behavioral design pattern.

Visitor Pattern Example Program

The example program displays a directory and file list.

Class Diagram
Visitor Pattern Class Diagram

The example defines an Element interface for data structures that accept visitors, a Visitor abstraction, file and directory entries, and a concrete visitor that traverses and prints the structure.

Advantages

Operations can be added by adding new visitors without changing the data structure classes. This is useful when the object structure is stable but the operations performed on it change often.