Visitor

Origin: GoF 95
Reason: To define new operations on the objects of a structure (as in a Composite) without changing the objects.
Synopsis: Each object, say obj, of the structure defines a method, conventionally called accept, that takes an object conventially called a visitor. The visitor, rather than obj, implements the new operation. Method accept dispatches the execution of the operation to the visitor.
Example: A document for word processing is a Composite whose nodes are paragraphs, lines, images, etc. To create the table of content of a document one can define an operation in each node class. The Visitor pattern allows one to define these operations in a separate, dedicated object.
Solution:
AbstractElement Interface or superclass of all classes in a Composite structure. Defines an accept method that takes a Visitor.
ConcreteElementi Class implementing AbstractElement and overriding the accept method.
Visitor Interface or superclass of all classes that perform an operation on the AbstractElement. Defines a family of visit methods each taking a ConcreteElement.
ConcreteVisitori Concrete subclass of Visitor for a specific operation. Overrides all the visit methods.
ObjectStructure An instance of this class is the object to be "visited". Most often is a Composite.
See also: Composite (often the object to be visited)
Little Language (often uses visitors)
Note: This is a complicated pattern that requires a good understanding of the concepts of overloading and overriding. The following code sketches the key elements of this pattern.

Interface of all visitable objects.

interface Element { void accept (Visitor v); }
Visitable classes. The type of "this" is bound at compile time.
class Element_1 implements Element {
    public void accept (Visitor v) { v.visit (this); }
}
    ...
class Element_n implements Element {
    public void accept (Visitor v) { v.visit (this); }
}
Interface of all visitors.
interface Visitor {
    void visit (Element_1 e);
    ...
    void visit (Element_n e);
}
Actual visitor class. Implements an operation that would otherwise be a member of each Element_i.
class MyVisitor implements Visitor {
      public void visit (Element_1 e) { ... }
      ...
      public void visit (Element_n e) { ... }
}
Sometimes methods accept and visit take one extra argument, an Object, and return a value, an Object.