Python Visitor Pattern
The Visitor pattern is a behavioral design pattern that lets you add new operations to existing class structures without modifying them. Simply put, the Visitor pattern separates an algorithm from the object structure it operates on.
Core idea
Imagine a scene where you go to a hospital for a checkup: you (the visitee) stay still, while different doctors (visitors) come to examine you. Each doctor focuses on their own specialty, but all examine the same you.
In programming, the Visitor pattern works in a similar way:
- The visited elementsRemain stable and unchanged
- VisitorsCan flexibly add new operations
- Elements accept visitors, allowing visitors to perform operations on them
Why We Need the Visitor Pattern
Limitations of the Traditional Approach
Suppose we have a graphics system containing various shapes:
Example
class
Circle:
def
init
(
self
,
radius
)
:
self
.
radius
=
radius
def
area
(
self
)
:
return
3.14
self
.
radius
self
.
radius
def
perimeter
(
self
)
:
return
2
3.14
self
.
radius
class
Rectangle:
def
init
(
self
,
width
,
height
)
:
self
.
width
=
width
self
.
height
=
height
def
area
(
self
)
:
return
self
.
width
self
.
height
def
perimeter
(
self
)
:
return
2
(
self
.
width
self
.
height
)
Here's the problem: If we want to add new functionality, such as computing the centroid of a shape or exporting to SVG, we would need to modify every shape class. This violates the Open-Closed Principle (open for extension, closed for modification).
Advantages of the Visitor Pattern
The Visitor pattern solves this problem in the following ways:
- Easy to add new operations: Just create a new visitor class without modifying existing element classes
- Related operations are managed centrally: Organize related operations in the same visitor
- Stable element structure: Element classes do not need frequent modification
Implementation of the Visitor Pattern
Basic structure
Let's understand the implementation of the Visitor pattern through a concrete example:
Example
from
abc
import
ABC
,
abstractmethod
1. Define the Element Interface
class
ShapeElement
(
ABC
)
:
@
abstractmethod
def
accept
(
self
,
visitor
)
:
pass
2. Define the Visitor Interface
class
ShapeVisitor
(
ABC
)
:
@
abstractmethod
def
visit_circle
(
self
,
circle
)
:
pass
@
abstractmethod
def
visit_rectangle
(
self
,
rectangle
)
:
pass
3. Concrete Element Classes
class
Circle
(
ShapeElement
)
:
def
init
(
self
,
radius
)
:
self
.
radius
=
radius
def
accept
(
self
,
visitor
)
:
visitor.
visit_circle
(
self
)
class
Rectangle
(
ShapeElement
)
:
def
init
(
self
,
width
,
height
)
:
self
.
width
=
width
self
.
height
=
height
def
accept
(
self
,
visitor
)
:
visitor.
visit_rectangle
(
self
)
4. Concrete Visitor Classes
class
AreaCalculator
(
ShapeVisitor
)
:
def
visit_circle
(
self
,
circle
)
:
area
=
3.14
- circle.
radius
- circle.
radius
(
f
"Circle area: {area:.2f}"
)
return
area
def
visit_rectangle
(
self
,
rectangle
)
:
area
=
rectangle.
width
- rectangle.
height
(
f
"Rectangle area: {area:.2f}"
)
return
area
class
PerimeterCalculator
(
ShapeVisitor
)
:
def
visit_circle
(
self
,
circle
)
:
perimeter
=
2
3.14
- circle.
radius
(
f
"Circle perimeter: {perimeter:.2f}"
)
return
perimeter
def
visit_rectangle
(
self
,
rectangle
)
:
perimeter
=
2
(
rectangle.
width
- rectangle.
height
)
(
f
"Rectangle perimeter: {perimeter:.2f}"
)
return
perimeter
Usage examples
Example
Create shape objects
shapes
=
[
Circle
(
5
)
,
Rectangle
(
4
,
6
)
,
Circle
(
3
)
]
Create visitors
area_calculator
=
AreaCalculator
(
)
perimeter_calculator
=
PerimeterCalculator
(
)
(
"=== Calculate area ==="
)
for
shape
in
shapes:
shape.
accept
(
area_calculator
)
(
"\n=== Calculate perimeter ==="
)
for
shape
in
shapes:
shape.
accept
(
perimeter_calculator
)
Output result:
=== 计算面积 ===
圆的面积: 78.50
矩形的面积: 24.00
圆的面积: 28.26
=== 计算周长 ===
圆的周长: 31.40
矩形的周长: 20.00
圆的周长: 18.84
Core Components of the Visitor Pattern
1. Visitor (Visitor Interface)
Defines the visit method for each concrete element class.
Example
class
ShapeVisitor
(
ABC
)
:
def
visit_circle
(
self
,
circle
)
:
pass
def
visit_rectangle
(
self
,
rectangle
)
:
pass
def
visit_triangle
(
self
,
triangle
)
:
pass
Easy to extend
2. ConcreteVisitor (Concrete Visitor)
Implements the operations defined in the visitor interface.
Example
class
ExportVisitor
(
ShapeVisitor
)
:
def
visit_circle
(
self
,
circle
)
:
return
f
'
def
visit_rectangle
(
self
,
rectangle
)
:
return
f
'
3. Element (Element Interface)
Defines the method for accepting a visitor.
Example
class
ShapeElement
(
ABC
)
:
@
abstractmethod
def
accept
(
self
,
visitor
)
:
pass
4. ConcreteElement (Concrete Element)
Implements the element interface and calls the visitor's corresponding method in the accept method.
Example
class
Circle
(
ShapeElement
)
:
def
accept
(
self
,
visitor
)
:
visitor.
visit_circle
(
self
)
Double dispatch occurs here
Advanced Application Example
A Complex Document Processing System
Let's look at a more practical example: processing different types of document elements.
Example
from
abc
import
ABC
,
abstractmethod
Document Element Interface
class
DocumentElement
(
ABC
)
:
@
abstractmethod
def
accept
(
self
,
visitor
)
:
pass
Concrete Document Elements
class
Paragraph
(
DocumentElement
)
:
def
init
(
self
,
text
)
:
self
.
text
=
text
def
accept
(
self
,
visitor
)
:
return
visitor.
visit_paragraph
(
self
)
class
Heading
(
DocumentElement
)
:
def
init
(
self
,
text
,
level
)
:
self
.
text
=
text
self
.
level
=
level
def
accept
(
self
,
visitor
)
:
return
visitor.
visit_heading
(
self
)
class
List
(
DocumentElement
)
:
def
init
(
self
,
items
)
:
self
.
items
=
items
def
accept
(
self
,
visitor
)
:
return
visitor.
visit_list
(
self
)
Visitor Interface
class
DocumentVisitor
(
ABC
)
:
@
abstractmethod
def
visit_paragraph
(
self
,
paragraph
)
:
pass
@
abstractmethod
def
visit_heading
(
self
,
heading
)
:
pass
@
abstractmethod
def
visit_list
(
self
,
list_element
)
:
pass
Concrete Visitor: HTML Export
class
HTMLExportVisitor
(
DocumentVisitor
)
:
def
visit_paragraph
(
self
,
paragraph
)
:
return
f
"
{paragraph.text}
"
def
visit_heading
(
self
,
heading
)
:
return
f
"
def
visit_list
(
self
,
list_element
)
:
items
=
""
.
join
(
f
"
for
item
in
list_element.
items
)
return
f
"
- {items}
Concrete Visitor: Word Count
class
WordCountVisitor
(
DocumentVisitor
)
:
def
init
(
self
)
:
self
.
total_words
=
0
def
visit_paragraph
(
self
,
paragraph
)
:
words
=
len
(
paragraph.
text
.
split
(
)
)
self
.
total_words
=
words
return
words
def
visit_heading
(
self
,
heading
)
:
words
=
len
(
heading.
text
.
split
(
)
)
self
.
total_words
=
words
return
words
def
visit_list
(
self
,
list_element
)
:
words
=
sum
(
len
(
item.
split
(
)
)
for
item
in
list_element.
items
)
self
.
total_words
=
words
return
words
Usage examples
document
=
[
Heading
(
"Python Tutorial"
,
1
)
,
Paragraph
(
"Python is a powerful programming language."
)
,
List
(
[
"List item 1"
,
"List item 2"
,
"List item 3"
]
)
,
Paragraph
(
"Learning Python is fun."
)
]
HTML Export
html_visitor
=
HTMLExportVisitor
(
)
(
"=== HTML Export ==="
)
for
element
in
document:
(
element.
accept
(
html_visitor
)
)
Word count
word_visitor
=
WordCountVisitor
(
)
(
"\n=== Word Count ==="
)
for
element
in
document:
words
=
element.
accept
(
word_visitor
)
(
f
"{element.class.name}: {words} words"
)
(
f
"Total words: {word_visitor.total_words}"
)
Pros and Cons of the Visitor Pattern
Advantages
- Open-Closed Principle: Easy to add new operations without modifying existing classes
- Single responsibility principle: Centralize related behavior in a single visitor class
- Flexibility: Different visitors can be chosen at runtime
- Data separation: Algorithms are separated from data structures
Disadvantages
- Element interfaces are hard to change: Adding a new element class requires modifying all visitors
- May break encapsulation: Visitors may need to access private members of elements
- Complexity: May seem overly complex for simple data structures
Applicable scenarios
Scenarios Suitable for the Visitor Pattern
- Stable object structure: Need to define multiple operations on a relatively stable object structure
- Frequently changing operations: Need to frequently add new operations or algorithms
- Related operations centralized: Want to organize related operations together
- Complex object structures: The object structure contains many different types of objects
Practical application cases
- Compilers: Various analyses on syntax trees (type checking, code optimization, etc.)
- Document processing: Different processing of document elements (export, statistics, formatting, etc.)
- GUI Systems: Different operations on UI components (rendering, event handling, etc.)
- Game Development: Different processing of game objects (collision detection, AI, etc.)
Best practices and notes
1. Use Double Dispatch
The core of the Visitor pattern is double dispatch:
- First dispatch: the element accepts the visitor
- Second dispatch: the visitor visits the concrete element
Example
In the element
def
accept
(
self
,
visitor
)
:
visitor.
visit_circle
(
self
)
The specific visit method is determined here
2. Handling Visitor State
If a visitor needs to maintain state:
Example
class
StatisticsVisitor
(
ShapeVisitor
)
:
def
init
(
self
)
:
self
.
total_area
=
0
self
.
shape_count
=
0
def
visit_circle
(
self
,
circle
)
:
area
=
3.14
- circle.
radius
- circle.
radius
self
.
total_area
=
area
self
.
shape_count
=
1
def
visit_rectangle
(
self
,
rectangle
)
:
area
=
rectangle.
width
- rectangle.
height
self
.
total_area
=
area
self
.
shape_count
=
1
def
get_statistics
(
self
)
:
return
{
'total_area'
:
self
.
total_area
,
'shape_count'
:
self
.
shape_count
,
'average_area'
:
self
.
total_area
/
self
.
shape_count
if
self
.
shape_count
0
else
0
}
3. Handling Visit Exceptions
Example
class
SafeVisitor
(
ShapeVisitor
)
:
def
visit_circle
(
self
,
circle
)
:
try
:
Perform the operation
pass
except
Exception
as
e:
(
f
"Error processing circle: {e}"
)
def
visit_rectangle
(
self
,
rectangle
)
:
try
:
Perform the operation
pass
except
Exception
as
e:
(
f
"Error processing rectangle: {e}"
)
Summary
The Visitor pattern is a powerful design pattern that provides great extensibility by separating algorithms from data structures. Although it has some complexity, in suitable scenarios it can significantly improve code maintainability and extensibility.
Key points:
- The Visitor pattern is suitable for scenarios where the object structure is stable but operations change frequently
- Polymorphic behavior is achieved through the double dispatch mechanism
- Easy to add new operations, but hard to add new element types
- In real projects, weigh its complexity against its benefits