Even if the visitor pattern can be applied to a list, it's usually associated to a Tree structure (Composites).
It separates the operation on the nodes of a tree from its structure. The node are then independent of the operations that apply to them.
The operations are packaged in a separate object, called a visitor. The visitor is then passed to the node of the tree as it’s traversed. If an node “accepts” the visitor, the visitor will then execute the operation for that node. (The node is an argument of the visitor method).
See Visitor
The visitor pattern extracts all operations on node from the tree structure because
Others:
With the Visitor pattern, you define two class hierarchies:
This is the key to the Visitor pattern: The operation that gets executed depends on both the type of Visitor and the type of Node it visits.
Effectively, the Visitor pattern lets you add operations to classes without changing them. In fact, some programming languages support it directly (CLOS, for example). Languages like C + + and Smalltalk support single-dispatch.
“Double-dispatch” simply means the operation that gets executed depends on:
Accept is a double-dispatch operation. Its meaning depends on two types:
An internal iterator will not cause double-dispatching— it will call an operation on the visitor with an element as an argument as opposed to calling an operation on the element with the visitor as an argument.
Often the object structure is responsible for iteration.
The main reason to put the traversal strategy in the visitor is to implement a particularly complex traversal, one that depends on the results of the operations on the object structure.