This pattern is licensed under the CC0 Public Domain Dedication.
Separate generic algorithms from the elements or structure on which they operate.
The visitor pattern allows generic algorithms to be implemented without modifying the objects on which they operate and supports different actions for each type of object without the need for dynamic casting.
element class, defined on lines 26–30, defines an interface that
allows an object to accept a visitor. Each class derived from
element, such as those on lines 32–48, implements the
function such that it calls the appropriate
visit function on the
Visitors, which implement the
visitor interface (lines 4–9),
represent algorithms to be applied to
elements. The visitor
visit overloads for each type of
visitor is defined on lines 11–23.
visitor visits an
element, two function calls are made
accept and one to
visit) and the final
that is called depends on the type of both the
element and the
visitor. This process is known as double dispatch.
The visitor pattern is particularly useful when the
part of a larger structure, in which case the
accept function can
call itself recursively down the structure.
09 December 2017