The Visitor Pattern is a behavioral Gang of Four (GoF) design pattern that allows you to add new operations or algorithms to an existing object structure without modifying those objects.
Imagine you have a complex tree structure of objects (like an Abstract Syntax Tree in a compiler, or a Document Object Model). You need to perform various operations across this tree: exporting it to XML, extracting metrics, or applying a transformation.
If you add an exportXML() and extractMetrics() method to every single node class, you violate the Single Responsibility Principle and pollute the data classes with unrelated business logic.
The Visitor pattern extracts these operations into a separate class called a Visitor.
It relies on a technique called Double Dispatch. In standard Object-Oriented languages (like Java or C#), method overloading is resolved at compile-time (Single Dispatch). The Visitor pattern uses two method calls to ensure the runtime executes the correct code based on both the type of the Visitor and the specific type of the Element.
accept(Visitor v) method.accept, the element calls v.visit(this). Because this is strongly typed to the specific element class at compile-time, the correct overloaded visit() method is triggered on the Visitor.The Visitor pattern is almost exclusively used in conjunction with the Composite Pattern, acting as the engine that traverses the composite tree.