Intent
- Allow to define new operations for a class hierarchy without modifying the hierarchy
Structure

- The concrete implementations of
accept(Visitor v)methods only need to callv.visit(this), then the calleeVisitorwill carry out the necessary operation on the callerComponent. This is the double dispatch technique, where the result of the call depends on the request and the types of two receivers, e.g.,ComponentandVisitorin this case. - Each
Visitorsupports a specific group of operations on theComponentclass hierarchy. Thus, new group of operations can be added via newVisitorwithout changing theComponenthierarchy at all.
Applicable contexts
- A class hierarchy rarely changes, but its services usually do.
Benefits
- Allow to extend the services of a whole class hierarchy without changing the hierarchy, because the extension can be done by adding new visitors
- Allow to modify the services of a whole class hierarchy without changing the hierarchy, because the modification can be done by adapting the corresponding visitors
Risks
- The pattern is quite complicated to understand. Using this pattern might make it hard for other team members to get familiar with the code.
- Adding new classes to the hierarchy causes changes to the whole visitor hierarchy, because new classes require new
visit()methods in theVisitorinterface and thus in all the existing visitors - If this pattern is used with the Composite pattern and the Composite contains a cycle in it, the accept-visit loop might be repeated forever.
Example
References
[1] Visitor, The GOF book
[2] Visitor, Chapter 29, Design Patterns In Java