访问者模式

访问者模式（visitor pattern），是一种将算法与对象结构分离的软件设计模式。在传统的单分派语言比如Smalltalk、Java和C++之中，访问者模式被用来模拟。在支持多分派的语言如CLOS之中，访问者模式就不再需要了。
概述.
访问者模式是一个由许多对象构成的对象结构，这些对象的类都拥有一个codice_1方法用来接受访问者对象；访问者是一个接口，它有一个codice_2方法，这个方法对访问到的对象结构中不同类型的元素作出相应的动作；在对象结构的访问过程中，codice_2方法遍历整个对象结构，对每一个元素都实施codice_1方法，在每一个元素的codice_1方法中回调访问者的codice_2方法，从而使访问者得以处理对象结构的每一个元素。我们可以针对对象结构设计不同的实在的访问者类来完成不同的操作。
结构.
在上面的UML类图中：
UML序列图展示了运行时交互：
例子.
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&lt;CarElement&gt; 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());
输出：
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的例子：
from abc import ABCMeta, abstractmethod
class CarElement(metaclass=ABCMeta):
 @abstractmethod
 def accept(self, visitor): pass
class CarElementVisitor(metaclass=ABCMeta):
 @abstractmethod
 def visit_body(self, element): pass
 @abstractmethod
 def visit_engine(self, element): pass
 @abstractmethod
 def visit_wheel(self, element): pass
 @abstractmethod
 def visit_car(self, element): pass
class Body(CarElement):
 def accept(self, visitor):
 visitor.visit_body(self)
class Engine(CarElement):
 def accept(self, visitor):
 visitor.visit_engine(self)
class Wheel(CarElement):
 def __init__(self, name):
 self.name = name
 def accept(self, visitor):
 visitor.visit_wheel(self)
class Car(CarElement):
 def __init__(self):
 self.elements = [
 Wheel("front left"), Wheel("front right"),
 Wheel("back left"), Wheel("back right"),
 Body(), Engine()]
 def accept(self, visitor):
 for element in self.elements:
 element.accept(visitor)
 visitor.visit_car(self)
class CarElementDoVisitor(CarElementVisitor):
 def visit_body(self, body):
 print("Moving my body.")
 def visit_car(self, car):
 print("Starting my car.")
 def visit_wheel(self, wheel):
 print(f"Kicking my {wheel.name} wheel.")
 def visit_engine(self, engine):
 print("Starting my engine.")
class CarElementPrintVisitor(CarElementVisitor):
 def visit_body(self, body):
 print("Visiting body.")
 def visit_car(self, car):
 print("Visiting car.")
 def visit_wheel(self, wheel):
 print(f"Visiting {wheel.name} wheel.")
 def visit_engine(self, engine):
 print("Visiting engine.")
其用例：
»&gt; car = Car()
»&gt; car.accept(CarElementPrintVisitor())
Visiting front left wheel.
Visiting front right wheel.
Visiting back left wheel.
Visiting back right wheel.
Visiting body.
Visiting engine.
Visiting car.
»&gt; car.accept(CarElementDoVisitor())
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.
C#.
下面的C#例子，声明了一个独立的codice_37类处理打印。如果想要介入一个新的具体访问者，则需要创建一个实现codice_38接口的新类，并且提供一个codice_39方法的新实现。现存的类（codice_40和codice_41）将保持不变。
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 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 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();