访问者模式

<image>

访问者模式（visitor pattern），是一种将算法与对象结构分离的软件设计模式。在传统的单分派语言比如Smalltalk、Java和C++之中，访问者模式被用来模拟双分派。在支持多分派的语言如CLOS之中，访问者模式就不再需要了。

## 概述

访问者模式是一个由许多对象构成的对象结构，这些对象的类都拥有一个`accept`方法用来接受访问者对象；访问者是一个接口，它有一个`visit`方法，这个方法对访问到的对象结构中不同类型的元素作出相应的动作；在对象结构的访问过程中，`visit`方法遍历整个对象结构，对每一个元素都实施`accept`方法，在每一个元素的`accept`方法中回调访问者的`visit`方法，从而使访问者得以处理对象结构的每一个元素。我们可以针对对象结构设计不同的实在的访问者类来完成不同的操作。

## 结构

<image>

在上面的UML类图中：

- `ElementA`类不直接实现新的运算，`ElementA`转而实现一个分派运算`accept(visitor)`，它将请求分配（委托）给被接受的访问者对象（`visitor.visitElementA(this)`）。`Visitor1`类实现这个运算（`visitElementA(e:ElementA)`）。
- `ElementB` 接着通过分派到`visitor.visitElementB(this)`实现`accept(visitor)`。`Visitor1`类实现这个运算（`visitElementB(e:ElementB)`）。

UML序列图展示了运行时交互：

- `Client`对象游历一个对象结构中的元素（`ElementA,ElementB`）并调用`accept(visitor)`于每个元素之上。
- 首先，`Client`调用`accept(visitor)`于`ElementA`之上，它调用`visitElementA(this)`于被接受的`visitor`对象之上。这个元素自身（`this`）被传递给`visitor`，使得它可以访问`ElementA`（调用`operationA()`）。
- 此后，`Client`调用`accept(visitor)`于`ElementB`之上，它调用`visitElementB(this)`于`visitor`之上，它访问`ElementB`（调用`operationB()`）。

## 例子

### Java

<image>

Java的例子：

```Java
import java.util.List;

interface CarElement {
    void accept(CarElementVisitor visitor);
}

interface CarElementVisitor {
    void visit(Body body);
    void visit(Car car);
    void visit(Engine engine);
    void visit(Wheel wheel);
}

class Wheel implements CarElement {
    private final String name;
    public Wheel(final String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    @Override
    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}

class Body implements CarElement {
    @Override
    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}

class Engine implements CarElement {
    @Override
    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}

class Car implements CarElement {
    private final List<CarElement> elements;
    public Car() {
        this.elements = List.of(
            new Wheel("front left"), new Wheel("front right"),
            new Wheel("back left"), new Wheel("back right"),
            new Body(), new Engine()
        );
    }
    @Override
    public void accept(CarElementVisitor visitor) {
        for (CarElement element : elements) {
            element.accept(visitor);
        }
        visitor.visit(this);
    }
}

class CarElementDoVisitor implements CarElementVisitor {
    @Override
    public void visit(Body body) {
        System.out.println("Moving my body");
    }
    @Override
    public void visit(Car car) {
        System.out.println("Starting my car");
    }
    @Override
    public void visit(Wheel wheel) {
        System.out.println("Kicking my " + wheel.getName() + " wheel");
    }
    @Override
    public void visit(Engine engine) {
        System.out.println("Starting my engine");
    }
}

class CarElementPrintVisitor implements CarElementVisitor {
    @Override
    public void visit(Body body) {
        System.out.println("Visiting body");
    }
    @Override
    public void visit(Car car) {
        System.out.println("Visiting car");
    }
    @Override
    public void visit(Engine engine) {
        System.out.println("Visiting engine");
    }
    @Override
    public void visit(Wheel wheel) {
        System.out.println("Visiting " + wheel.getName() + " wheel");
    }
}

public class VisitorDemo {
    public static void main(final String[] args) {
        Car car = new Car();
        car.accept(new CarElementPrintVisitor());
        car.accept(new CarElementDoVisitor());
    }
}
```

输出：

```output
Visiting front left wheel
Visiting front right wheel
Visiting back left wheel
Visiting back right wheel
Visiting body
Visiting engine
Visiting car
Kicking my front left wheel
Kicking my front right wheel
Kicking my back left wheel
Kicking my back right wheel
Moving my body
Starting my engine
Starting my car
```

### Python

Python的例子：

```python
from abc import ABC, abstractmethod
from functools import singledispatchmethod

class Element():
    def accept(self, visitor):
        visitor.visit(self)

class Body(Element): pass

class Engine(Element): pass

class Wheel(Element):
    def __init__(self, name):
        self.name = name

class ObjectStructure(ABC):
    @abstractmethod
    def __init__(self):
        self.element_list = []
    def __call__(self, visitor):
        for element in self.element_list:
            element.accept(visitor)
        self.accept(visitor)

class Car(Element, ObjectStructure):
    def __init__(self):
        self.element_list = [
            Wheel("front left"), Wheel("front right"),
            Wheel("back left"), Wheel("back right"),
            Body(), Engine()]

class Visitor(ABC):
    @abstractmethod
    def visit(self, element): pass

class PrintVisitor(Visitor): 
    @singledispatchmethod
    def visit(self, element): pass

@PrintVisitor.visit.register
def _(self, body :Body):
    print(f"Visiting body.")
@PrintVisitor.visit.register
def _(self, car :Car):
    print(f"Visiting car.")
@PrintVisitor.visit.register
def _(self, wheel :Wheel):
    print(f"Visiting {wheel.name} wheel.")
@PrintVisitor.visit.register
def _(self, engine :Engine):
    print(f"Visiting engine.")

class DoVisitor(Visitor):
    @singledispatchmethod
    def visit(self, element): pass
    
@DoVisitor.visit.register
def _(self, body :Body):
    print(f"Moving my body.")
@DoVisitor.visit.register
def _(self, car :Car):
    print(f"Starting my car.")
@DoVisitor.visit.register
def _(self, wheel :Wheel):
    print(f"Kicking my {wheel.name} wheel.")
@DoVisitor.visit.register
def _(self, engine: Engine):
    print(f"Starting my engine.")
```

这个实现通过采用标准库`functools`中的`singledispatchmethod`，将方法变换为单一分派泛化函数，动态的每个具体访问者扩展方法上对应每个具体元素的方法。下面是其用例：

```pycon
>>> car = Car()
>>> car(PrintVisitor())
Visiting front left wheel.
Visiting front right wheel.
Visiting back left wheel.
Visiting back right wheel.
Visiting body.
Visiting engine.
Visiting car.
>>> car(DoVisitor())
Kicking my front left wheel.
Kicking my front right wheel.
Kicking my back left wheel.
Kicking my back right wheel.
Moving my body.
Starting my engine.
Starting my car.
```

下面的例子通过命名约定采用了反射式实现方式：

```python
from abc import ABC, abstractmethod

class Element():
    def accept(self, visitor):
        key = '_'+type(self).__name__+'__visit'
        if key in visitor.__dir__():
            visitor.__getattribute__(key)(self)

class Body(Element): pass

class Engine(Element): pass

class Wheel(Element):
    def __init__(self, name):
        self.name = name

class ObjectStructure(ABC):
    @abstractmethod
    def __init__(self):
        self.element_list = []
    def __call__(self, visitor):
        for element in self.element_list:
            element.accept(visitor)
        self.accept(visitor)

class Car(Element, ObjectStructure):
    def __init__(self):
        self.element_list = [
            Wheel("front left"), Wheel("front right"),
            Wheel("back left"), Wheel("back right"),
            Body(), Engine()]

class Visitor():
    @classmethod
    def register(cls, *visitor_list):
        nmlist = ['_'+x.__name__+'__visit' 
            for x in Element.__subclasses__()]
        for fn in visitor_list:
            if fn.__name__ in nmlist:
                type.__setattr__(cls, fn.__name__, fn)
                del globals()[fn.__name__]

class PrintVisitor(Visitor): pass
def _Body__visit(self, body):
    print(f"Visiting body.")
def _Car__visit(self, car):
    print(f"Visiting car.")
def _Wheel__visit(self, wheel):
    print(f"Visiting {wheel.name} wheel.")
def _Engine__visit(self, engine):
    print(f"Visiting engine.")
PrintVisitor.register(_Body__visit, _Car__visit,
    _Wheel__visit, _Engine__visit)

class DoVisitor(Visitor): pass
def _Body__visit(self, body):
    print(f"Moving my body.")
def _Car__visit(self, car):
    print(f"Starting my car.")
def _Wheel__visit(self, wheel):
    print(f"Kicking my {wheel.name} wheel.")
def _Engine__visit(self, engine):
    print(f"Starting my engine.")
DoVisitor.register(_Body__visit, _Car__visit,
    _Wheel__visit, _Engine__visit)
```

### C#

下面的C#例子，声明了一个独立的`ExpressionPrintingVisitor`类处理打印。如果想要介入一个新的具体访问者，则需要创建一个实现`Visitor`接口的新类，并且提供一个`Visit`方法的新实现。现存的类（`Literal`和`Addition`）将保持不变。

```csharp
using System;

namespace Wikipedia;

public interface Visitor {
    void Visit(Literal literal);  
    void Visit(Addition addition);
}

public class ExpressionPrintingVisitor : Visitor {
    public void Visit(Literal literal) {
        Console.WriteLine(literal.Value);
    }

    public void Visit(Addition addition) {
        double leftValue = addition.Left.GetValue();
        double rightValue = addition.Right.GetValue();
        var sum = addition.GetValue();
        Console.WriteLine($"{leftValue} + {rightValue} = {sum}");
    }
}

public abstract class Expression {
    public abstract void Accept(Visitor v);
   
    public abstract double GetValue();
}

public class Literal : Expression {
    public Literal(double value) {
        this.Value = value;
    }

    public double Value { get; set; }

    public override void Accept(Visitor v) {
        v.Visit(this);
    }
 
    public override double GetValue() {
        return Value;
    }
}

public class Addition : Expression {
    public Addition(Expression left, Expression right) {
        Left = left;
        Right = right;
    }

    public Expression Left { get; set; }
    public Expression Right { get; set; }

    public override void Accept(Visitor v) {
        Left.Accept(v);
        Right.Accept(v);
        v.Visit(this);
    }
  
    public override double GetValue() {
        return Left.GetValue() + Right.GetValue();
    }
}

public static class Program {
    public static void Main(string[] args) {
        // Emulate 1 + 2 + 3
        var e = new Addition(
            new Addition(
                new Literal(1),
                new Literal(2)
            ),
            new Literal(3)
        );

        var printingVisitor = new ExpressionPrintingVisitor();
        e.Accept(printingVisitor);
        Console.ReadKey();
    }
}
```

## 参考条目

- 合成模式
- 桥接模式
- 多分派