ConceptDifficulty: Intermediate1 min

Visitor Pattern Structure: The Class and Sequence Diagrams

Each element's accept(v) calls v.visitThisKind(this), which is how the right method is found.

Visitor has four participants: the visitor interface, the concrete visitors, the element interface, and the concrete elements. This card reads their roles off the Gang of Four's class diagram, then traces the two calls, together called double dispatch, that choose the code to run for a given element and a given visitor.

Visitor participants
Each participant and its role
ParticipantRoleIn the diagram
VisitorDeclares one visit method per concrete element class.Visitor
Concrete VisitorOne operation, with its code for each element class.AreaVisitor
ElementDeclares accept(visitor).Element
Concrete ElementImplements accept by calling the visit method for its own class.Circle, Square

Dispatch is choosing which method body runs for a call. An ordinary method call dispatches once, on the type of the object it is called on. Visitor needs the code chosen by two types, the element's and the visitor's, so it makes two calls, each dispatching on one of them.

The sequence diagram follows an area visitor over a circle and a square. The first call, accept, is answered by the element's class; inside it, the element calls the one visit method that names its own class, and that second call is answered by the visitor's class.

Double dispatch over two elements

The loop never asks what kind of shape it holds. It calls accept on each, and the right method of the right visitor runs. That is why every concrete element needs its own one-line accept: it is the only place that knows the element's class.