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.
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 diagram | What it is | What it does |
|---|---|---|
| Client | The code that owns the object structure | Creates a visitor and passes it to each element through accept. It usually works with elements through their interface, without knowing their concrete classes. |
| Shape | The element interface | Declares accept(v: Visitor), the one method every element needs for any number of future operations. |
| Visitor | The visitor interface | Declares one visiting method per concrete element class. |
| Circle | A concrete element | Implements accept by calling v.visitCircle(this), which tells the visitor its class. |
| Rectangle | A concrete element | Implements accept by calling v.visitRectangle(this). |
| XmlExportVisitor | A concrete visitor: one operation | Holds the XML export code for every shape class in one place. |
| AreaVisitor | A concrete visitor: another operation | Adds 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.
- The client calls
shape.accept(visitor)on an element it knows only as aShape. - The call is dispatched on the element's class. If the shape is a circle,
Circle.acceptruns. Circle.acceptcallsvisitor.visitCircle(this), passing itself.- 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.
| Pros | Cons |
|---|---|
| Open/closed principle: new behaviour for existing classes without changing them | Every 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 class | Visitors 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 tree | In 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
- You need to perform an operation on all elements of a complex object structure, such as an object tree.
- Many unrelated operations are needed, and new ones are added frequently.
- The classes that make up the structure are known and not expected to change.
- You want auxiliary behaviour, such as export, kept out of the main classes.
Skip it when
- New element classes are added often: each one forces a change to every visitor.
- The operation needs private state that the elements should not expose.
- Your language has sum types and pattern matching, which remove much of the need for the pattern.
What are common mistakes with the visitor pattern?
Most problems come from an unstable element hierarchy or from a broken accept method.
- Not overriding
acceptin every concrete element. Even if a base class implements it, each subclass must override it and call the visit method for its own class. - Using it on a hierarchy that keeps growing. Each new element class means editing every visitor.
- Making fields public just for the visitor, which breaks the element's encapsulation.
- Letting elements depend on concrete visitors. Elements should know only the visitor interface.
- Using it for one or two fixed operations. The pattern pays off when many unrelated operations are needed and new ones keep arriving.
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.
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.