Explained with a diagram · Design patterns

Visitor pattern: UML class diagram and how it works

In short

The visitor pattern is a behavioural design pattern that separates an algorithm from the object structure it operates on. Each operation becomes a visitor object with one visit method per element class, and every element has an accept(visitor) method that calls the visit method matching its own class. New operations can then be added without changing the element classes. It is one of the twenty-three Gang of Four design patterns and works through double dispatch.

Updated · by the ChartCraft team · one of the patterns and models explained with a diagram

What does the visitor pattern look like as a UML class diagram?

The class diagram has two parallel hierarchies. On one side is the element interface with its concrete elements, here Shape, Circle and Rectangle. On the other is the visitor interface with one concrete visitor per operation. The element interface depends on the visitor interface through accept.

Visitor pattern UML class diagram: a Visitor interface with two concrete visitors, a Shape element interface with Circle and Rectangle, and a clientAreaVisitor+total: float+visitCircle(c: Circle)+visitRectangle(r: Rectangle)Visitor+visitCircle(c: Circle)+visitRectangle(r: Rectangle)Client+exportAll()Shape+accept(v: Visitor)Circle+radius: float+accept(v: Visitor)Rectangle+width: float+height: float+accept(v: Visitor)XmlExportVisitor+visitCircle(c: Circle)+visitRectangle(r: Rectangle)implementsimplementsaccept calls visitimplementsimplementscalls accept
Visitor pattern: two hierarchies. Elements (Shape) expose accept; visitors hold one visit method per element class. This static rendering draws every relationship as a labelled arrow; the Mermaid code below carries the UML arrow types. Rendered by ChartCraft's layout engine.

Mermaid code for this diagram

classDiagram
    class AreaVisitor {
        +total: float
        +visitCircle(c: Circle)
        +visitRectangle(r: Rectangle)
    }
    class Visitor {
        <<interface>>
        +visitCircle(c: Circle)
        +visitRectangle(r: Rectangle)
    }
    class Client {
        +exportAll()
    }
    class Shape {
        <<interface>>
        +accept(v: Visitor)
    }
    class Circle {
        +radius: float
        +accept(v: Visitor)
    }
    class Rectangle {
        +width: float
        +height: float
        +accept(v: Visitor)
    }
    class XmlExportVisitor {
        +visitCircle(c: Circle)
        +visitRectangle(r: Rectangle)
    }
    Visitor <|.. XmlExportVisitor : implements
    Shape <|.. Circle : implements
    Visitor <.. Shape : accept calls visit
    Shape <|.. Rectangle : implements
    Visitor <|.. AreaVisitor : implements
    Shape <-- Client : calls accept

Paste it into any Mermaid renderer, or check and export it with the Mermaid syntax checker and Mermaid to PNG.

What are the participants in the visitor pattern?

There are five roles: the visitor interface, concrete visitors, the element interface, concrete elements and the client. In this example the elements are shapes and the operations are XML export and area calculation.

Part of the diagramWhat it isWhat it does
ClientThe code that owns the object structureCreates a visitor and passes it to each element through accept. It usually works with elements through their interface, without knowing their concrete classes.
ShapeThe element interfaceDeclares accept(v: Visitor), the one method every element needs for any number of future operations.
VisitorThe visitor interfaceDeclares one visiting method per concrete element class.
CircleA concrete elementImplements accept by calling v.visitCircle(this), which tells the visitor its class.
RectangleA concrete elementImplements accept by calling v.visitRectangle(this).
XmlExportVisitorA concrete visitor: one operationHolds the XML export code for every shape class in one place.
AreaVisitorA concrete visitor: another operationAdds up areas as it visits each shape. A visitor can accumulate state while it works through the structure.

How does double dispatch work in the visitor pattern?

The method that finally runs is chosen by two types: the class of the element and the class of the visitor. That takes two calls, accept and then visit.

  1. The client calls shape.accept(visitor) on an element it knows only as a Shape.
  2. The call is dispatched on the element's class. If the shape is a circle, Circle.accept runs.
  3. Circle.accept calls visitor.visitCircle(this), passing itself.
  4. That call is dispatched on the visitor's class. If the visitor is an AreaVisitor, its circle code runs.

What are the pros and cons of the visitor pattern?

The visitor pattern makes operations easy to add and element classes hard to add. Adding an operation means one new visitor class; adding an element class means a new method in every existing visitor.

ProsCons
Open/closed principle: new behaviour for existing classes without changing themEvery visitor must be updated when a class is added to or removed from the element hierarchy
Single responsibility: all versions of one behaviour live in one classVisitors may lack access to the private fields and methods of the elements they work on
A visitor can gather information as it traverses a structure such as an object treeIn languages with sum types and pattern matching, much of the benefit disappears

When should you use the visitor pattern?

Use it when you have a stable set of element classes and keep needing new, unrelated operations over all of them, as in a drawing made of shapes or any other tree of objects.

Use it when

Skip it when

What are common mistakes with the visitor pattern?

Most problems come from an unstable element hierarchy or from a broken accept method.

How do you draw a visitor pattern class diagram?

Draw the element interface and its concrete classes, then the visitor interface and one concrete visitor per operation, connect each implementation to its interface with a realisation arrow, then add the dependency from the element interface to the visitor interface and the client's association with the elements.

Opens the studio with your text · or start from the Class diagram generator

What do real design pattern class diagrams look like?

Live diagrams from the public ChartCraft gallery, each generated from a plain-English description. Open one to see the prompt that produced it.

Questions

What is the visitor pattern?

The visitor pattern is a behavioural design pattern that separates an algorithm from the objects it operates on. The Gang of Four define it as representing an operation to be performed on the elements of an object structure, so that a new operation can be defined without changing the classes of those elements.

What is the visitor pattern used for?

It is used to run operations across a structure of objects of different classes, for example exporting every shape in a drawing to XML or computing a result over a tree of nodes. Each operation is written once, in its own visitor class, instead of being spread over all the element classes.

What is double dispatch in the visitor pattern?

Double dispatch means the code that runs depends on two runtime types: the element and the visitor. The client calls accept on the element, and the element calls the visit method for its own class on the visitor, so both types are resolved.

What are the disadvantages of the visitor pattern?

Adding a new element class is costly, because every visitor needs a new visit method. Visitors may also need access to private fields of the elements, which can force you to weaken encapsulation.

Is the visitor pattern a behavioral pattern?

Yes. Visitor is classed as a behavioural design pattern, and it is one of the twenty-three Gang of Four design patterns.

More patterns and models explained with a diagram

Describe the system in plain English and get the diagram.

Class diagram generator →