Visitor
In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure upon which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. Thus, using the visitor pattern helps conformance with the open/closed principle.
In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch.
While powerful, the visitor pattern is more limited than conventional virtual functions. It is not possible to create visitors for objects without adding a small callback method inside each class and the callback method in each of the classes is not inheritable.
The purpose of the Visitor Pattern is to encapsulate an operation that you want to perform on the elements of a data structure. In this way, you can change the operation being performed on a structure without the need of changing the classes of the elements that you are operating on. Using a Visitor pattern allows you to decouple the classes for the data structure and the algorithms used upon them.
Each node in the data structure "accepts" a Visitor, which sends a message to the Visitor which includes the node's class. The visitor will then execute its algorithm for that element. This process is known as "Double Dispatching." The node makes a call to the Visitor, passing itself in, and the Visitor executes its algorithm on the node. In Double Dispatching, the call made depends upon the type of the Visitor and of the Host (data structure node), not just of one component.
One key advantage of using the Visitor Pattern is that adding new operations to perform upon your data structure is very easy. All you have to do is create a new Visitor and define the operation there. This is the result of the very distinct separation of variant and invariant behavior in the Visitor pattern. The invariant behaviors are represented by the data structure elements and the abstract Visitor. The variant behaviors are encapsulated in the concrete Visitors.
Every Visitor has a method for every data structure element type. The data structure elements however, only deal with the abstract Visitor, and hence only have one method (accept()) that deals with it. That method is overriden in each concrete element, which only calls its respective method in the Visitor.
