Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Visitor Pattern

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:


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:


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

radius

radius

       

print

(

f

"Circle area: {area:.2f}"

)

       

return

area

   

   

def

visit_rectangle

(

self

,

rectangle

)

:

        area

=

rectangle.

width

height

       

print

(

f

"Rectangle area: {area:.2f}"

)

       

return

area

class

PerimeterCalculator

(

ShapeVisitor

)

:

   

def

visit_circle

(

self

,

circle

)

:

        perimeter

=

2

3.14

radius

       

print

(

f

"Circle perimeter: {perimeter:.2f}"

)

       

return

perimeter

   

   

def

visit_rectangle

(

self

,

rectangle

)

:

        perimeter

=

2

(

rectangle.

width

height

)

       

print

(

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

(

)

print

(

"=== Calculate area ==="

)

for

shape

in

shapes:

    shape.

accept

(

area_calculator

)

print

(

"\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

"{heading.text}"

   

   

def

visit_list

(

self

,

list_element

)

:

        items

=

""

.

join

(

f

"

  • {item}
  • "

    for

    item

    in

    list_element.

    items

    )

           

    return

    f

    "

    "

    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

    (

    )

    print

    (

    "=== HTML Export ==="

    )

    for

    element

    in

    document:

       

    print

    (

    element.

    accept

    (

    html_visitor

    )

    )

    Word count

    word_visitor

    =

    WordCountVisitor

    (

    )

    print

    (

    "\n=== Word Count ==="

    )

    for

    element

    in

    document:

        words

    =

    element.

    accept

    (

    word_visitor

    )

       

    print

    (

    f

    "{element.class.name}: {words} words"

    )

    print

    (

    f

    "Total words: {word_visitor.total_words}"

    )


    Pros and Cons of the Visitor Pattern

    Advantages

    1. Open-Closed Principle: Easy to add new operations without modifying existing classes
    2. Single responsibility principle: Centralize related behavior in a single visitor class
    3. Flexibility: Different visitors can be chosen at runtime
    4. Data separation: Algorithms are separated from data structures

    Disadvantages

    1. Element interfaces are hard to change: Adding a new element class requires modifying all visitors
    2. May break encapsulation: Visitors may need to access private members of elements
    3. Complexity: May seem overly complex for simple data structures

    Applicable scenarios

    Scenarios Suitable for the Visitor Pattern

    1. Stable object structure: Need to define multiple operations on a relatively stable object structure
    2. Frequently changing operations: Need to frequently add new operations or algorithms
    3. Related operations centralized: Want to organize related operations together
    4. Complex object structures: The object structure contains many different types of objects

    Practical application cases


    Best practices and notes

    1. Use Double Dispatch

    The core of the Visitor pattern is double dispatch:

    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

    radius

    radius

           

    self

    .

    total_area

    =

    area

           

    self

    .

    shape_count

    =

    1

       

       

    def

    visit_rectangle

    (

    self

    ,

    rectangle

    )

    :

            area

    =

    rectangle.

    width

    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:

               

    print

    (

    f

    "Error processing circle: {e}"

    )

       

       

    def

    visit_rectangle

    (

    self

    ,

    rectangle

    )

    :

           

    try

    :

               

    Perform the operation

               

    pass

           

    except

    Exception

    as

    e:

               

    print

    (

    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: