Visitor pattern is a behavioral pattern that lets you define a new operation to apply toward classes of the elements (Element Class, a.k.a. Visitable Class) without changing the classes of the elements on which it operates. The new operations are grouped together each is called a separate Visitor class.
Visitor pattern lets you add a new operation to a structure of objects (Visitable/Elements) to be traversed through, without changing the Visitable/Element on which it operates.
Visitor class separates out would-be virtual functions into a Visitor class.
Each Visitable/Element should implement an accept(Visitor) function which delegate the request to the underlying Visitor class via calling visitor.visit(this) from accept(Visitor).
Each concrete Visitor class implements a set of visit(Object) functions that does the real work for the operation to be applied to the structure of objects. Each visit(Object) function takes in a different type of concrete Visitable/Element object. The Visitor can optionally maintain a context during a traversal.
Consider a compiler program that deals with an abstract syntax tree. Each node in the abstract syntax tree may be a variable, an assignment, arithmetic expression, etc. For each node element, you want to apply operations like type-checking, code optimization, pretty-formatting, etc.
One way of structuring the above is to have a node class hierarchy. Within node class hierarchy, for each different node class, you define its type-checking operation, code optimization operation, and pretty-formatting operation inside the node class. This has three potential drawbacks:
To avoid the above drawbacks, apply the Visitor pattern which defines two class hierarchies: one (the visitable Element hierarchy) for the nodes or data structure being operated on and one (the Visitor hierarchy) for defining operations to be applied to the elements. The delegation of the operation from an element class to a visitor class is through an accept(Visitor) function defined in the element class. Then in terms, calls into Visitor.visit(this). When you need to introduce a new type of operation, you'd create a new subclass in the Visitor hierarchy, without needing to modify the Element hierarchy.
visotor pattern code sample
The element/visitable interface simply defines an accept method to allow the visitor to run some action over that element - the ConcreteElement will implement this accept method.
// Element Interface
 Delegate operation applied to an element to a corresponding visitor class.
 Visitor class holds local state. In this case, to accumulate postage cost.
 Request the result of the operation/computation/local state.
Visitor Pattern vs. Non-Visitor Pattern
when to use visitor pattern
Choose to use Visitor pattern if: