Intent - To define a set of actions in a
maintainable way that can be
taken against a family of classes. Visitor lets you
define a new operation without changing the classes of the
elements on which it operates. The Visitor will act on
data in other classes.
Problem -
an object structure contains many classes of objects
with differing interfaces, and you want to perform
operations on these objects that depend on their
concrete classes
several non-trivial actions need to be taken against
this group of classes.
The actions to be taken change depending on the
classes that they are being taken against.
The classes defining the object structure rarely
change, so removing the operation from the objects is
not as dangerous.
Solution -
Define a set of actions using two class heirarchies, one
for the elements being operated on, and one for the
visitors that define the operations on the elements.
New operations are defined by adding a new subclass to
visitory class heirarchy.
Participants and Collaborators
Visitor
ConcreteVisitor
Element
ConcreteElement
ObjectStructure
Consequences
Visitor makes adding new operations easy
A visitor gathers related operations and separates
unrelated ones
Adding new ConcreteElement classes is hard - Visitor
is not a good idea if you will be adding many new
classes to your program
Visiting across class hierarchies
Accumulating state
Breaking encapsulation
Implementation
Double dispatch - the operation that gets executed
depends on the types of both the Visitor and the
Element. Double dispatching lets visitors request
different operations on each class of element.