访问者模式中accept()方法的意义是什么? [英] What is the point of accept() method in Visitor pattern?

查看:34
本文介绍了访问者模式中accept()方法的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多关于将算法与类解耦的讨论.但是,有一件事没有解释.

There is a lot of talk on decoupling the algorithms from the classes. But, one thing stays aside not explained.

他们像这样使用访问者

abstract class Expr {
  public <T> T accept(Visitor<T> visitor) { return visitor.visit(this); }
}

class ExprVisitor extends Visitor{
  public Integer visit(Num num) {
    return num.value;
  }

  public Integer visit(Sum sum) {
    return sum.getLeft().accept(this) + sum.getRight().accept(this);
  }

  public Integer visit(Prod prod) {
    return prod.getLeft().accept(this) * prod.getRight().accept(this);
  }

Visitor 不是直接调用visit(element),而是要求元素调用它的visit 方法.它与公开的阶级不了解访客的想法相矛盾.

Instead of calling visit(element) directly, Visitor asks the element to call its visit method. It contradicts the declared idea of class unawareness about visitors.

PS1 请用你自己的话解释或指出准确的解释.因为我得到的两个回复涉及一般性和不确定性.

PS1 Please explain with your own words or point to exact explanation. Because two responses I got refer to something general and uncertain.

PS2 我的猜测:由于 getLeft() 返回基本的 Expression,调用 visit(getLeft()) 将导致 visit(Expression),而 getLeft() 调用 visit(this) 将导致另一个更合适的访问调用.因此,accept() 执行类型转换(也称为强制转换).

PS2 My guess: Since getLeft() returns the basic Expression, calling visit(getLeft()) would result in visit(Expression), whereas getLeft() calling visit(this) will result in another, more appropriate, visit invocation. So, accept() performs the type conversion (aka casting).

PS3 Scala 的模式匹配 = 类固醇上的访客模式 显示了没有接受方法的访问者模式是多么简单.维基百科对此声明进行了补充:通过链接显示接受"的论文() 方法在反射可用时是不必要的;为该技术引入术语Walkabout"."

PS3 Scala's Pattern Matching = Visitor Pattern on Steroid shows how much simpler the Visitor pattern is without the accept method. Wikipedia adds to this statement: by linking a paper showing "that accept() methods are unnecessary when reflection is available; introduces term 'Walkabout' for the technique."

推荐答案

访问者模式的 visit/accept 结构是类 C 语言的必要之恶(C#、Java 等)语义.访问者模式的目标是使用双重调度来路由您的呼叫,正如您在阅读代码时所期望的那样.

The visitor pattern's visit/accept constructs are a necessary evil due to C-like languages' (C#, Java, etc.) semantics. The goal of the visitor pattern is to use double-dispatch to route your call as you'd expect from reading the code.

通常,当使用访问者模式时,会涉及一个对象层次结构,其中所有节点都源自基本的 Node 类型,以下称为 Node.本能地,我们会这样写:

Normally when the visitor pattern is used, an object hierarchy is involved where all the nodes are derived from a base Node type, referred to henceforth as Node. Instinctively, we'd write it like this:

Node root = GetTreeRoot();
new MyVisitor().visit(root);

问题就在这里.如果我们的 MyVisitor 类定义如下:

Herein lies the problem. If our MyVisitor class was defined like the following:

class MyVisitor implements IVisitor {
  void visit(CarNode node);
  void visit(TrainNode node);
  void visit(PlaneNode node);
  void visit(Node node);
}

如果在运行时,不管 root 是什么实际类型,我们的调用都会进入重载 visit(Node node).这对于声明为 Node 类型的所有变量都是正确的.为什么是这样?因为 Java 和其他类似 C 的语言在决定调用哪个重载时只考虑参数的静态类型,或变量声明为的类型.Java 不会在运行时对每个方法调用采取额外的步骤,好吧,root 的动态类型是什么?哦,我明白了.它是一个 TrainNode.让我们看看 MyVisitor 中是否有任何方法接受 TrainNode... 类型的参数.编译器在编译时确定要调用的方法.(如果 Java 确实检查了参数的动态类型,性能会非常糟糕.)

If, at runtime, regardless of the actual type that root is, our call would go into the overload visit(Node node). This would be true for all variables declared of type Node. Why is this? Because Java and other C-like languages only consider the static type, or the type that the variable is declared as, of the parameter when deciding which overload to call. Java doesn't take the extra step to ask, for every method call, at runtime, "Okay, what is the dynamic type of root? Oh, I see. It's a TrainNode. Let's see if there's any method in MyVisitor which accepts a parameter of type TrainNode...". The compiler, at compile-time, determines which is the method that will be called. (If Java indeed did inspect the arguments' dynamic types, performance would be pretty terrible.)

Java 确实为我们提供了一种工具,用于在调用方法时考虑对象的运行时(即动态)类型 -- 虚拟方法调度.当我们调用一个虚方法时,调用实际上会转到内存中由函数指针组成的.每种类型都有一个表.如果某个特定方法被类覆盖,则该类的函数表条目将包含被覆盖函数的地址.如果该类没有覆盖一个方法,它将包含一个指向基类实现的指针.这仍然会导致性能开销(每个方法调用基本上都会取消引用两个指针:一个指向类型的函数表,另一个指向函数本身),但它仍然比检查参数类型要快.

Java does give us one tool for taking into account the runtime (i.e. dynamic) type of an object when a method is called -- virtual method dispatch. When we call a virtual method, the call actually goes to a table in memory that consists of function pointers. Each type has a table. If a particular method is overridden by a class, that class' function table entry will contain the address of the overridden function. If the class doesn't override a method, it will contain a pointer to the base class' implementation. This still incurs a performance overhead (each method call will basically be dereferencing two pointers: one pointing to the type's function table, and another of function itself), but it's still faster than having to inspect parameter types.

访问者模式的目标是实现双重调度——不仅是考虑的调用目标的类型(MyVisitor,通过虚拟方法),还有参数的类型(我们在看什么类型的 Node)?访问者模式允许我们通过 visit/accept 组合来做到这一点.

The goal of the visitor pattern is to accomplish double-dispatch -- not only is the type of the call target considered (MyVisitor, via virtual methods), but also the type of the parameter (what type of Node are we looking at)? The Visitor pattern allows us to do this by the visit/accept combination.

通过将我们的行更改为:

By changing our line to this:

root.accept(new MyVisitor());

我们可以得到我们想要的:通过虚方法分派,我们输入子类实现的正确accept()调用——在我们带有TrainElement的例子中,我们将输入TrainElementaccept() 的实现:

We can get what we want: via virtual method dispatch, we enter the correct accept() call as implemented by the subclass -- in our example with TrainElement, we'll enter TrainElement's implementation of accept():

class TrainNode extends Node implements IVisitable {
  void accept(IVisitor v) {
    v.visit(this);
  }
}

此时编译器知道什么,在TrainNodeaccept 范围内?它知道this的静态类型是一个TrainNode.这是编译器在我们的调用者范围内不知道的重要附加信息:在那里,它只知道 root 是一个 Node.现在编译器知道this (root) 不仅仅是一个Node,而是一个TrainNode.因此,在 accept() 中找到的一行:v.visit(this),完全意味着别的东西.编译器现在将查找采用 TrainNodevisit() 重载.如果它找不到,它就会将调用编译为一个带有 Node 的重载.如果两者都不存在,您将收到编译错误(除非您有一个采用 object 的重载).因此,执行将进入我们一直以来的意图:MyVisitorvisit(TrainNode e) 的实现.不需要演员表,最重要的是,不需要反思.因此,这种机制的开销相当低:它只包含指针引用,没有其他任何东西.

What does the compiler know at this point, inside the scope of TrainNode's accept? It knows that the static type of this is a TrainNode. This is an important additional shred of information that the compiler was not aware of in our caller's scope: there, all it knew about root was that it was a Node. Now the compiler knows that this (root) is not just a Node, but it's actually a TrainNode. In consequence, the one line found inside accept(): v.visit(this), means something else entirely. The compiler will now look for an overload of visit() that takes a TrainNode. If it can't find one, it'll then compile the call to an overload that takes a Node. If neither exist, you'll get a compilation error (unless you have an overload that takes object). Execution will thus enter what we had intended all along: MyVisitor's implementation of visit(TrainNode e). No casts were needed, and, most importantly, no reflection was needed. Thus, the overhead of this mechanism is rather low: it only consists of pointer references and nothing else.

你的问题是对的——我们可以使用演员表并获得正确的行为.然而,很多时候,我们甚至不知道 Node 是什么类型.以以下层次结构为例:

You're right in your question -- we can use a cast and get the correct behavior. However, often, we don't even know what type Node is. Take the case of the following hierarchy:

abstract class Node { ... }
abstract class BinaryNode extends Node { Node left, right; }
abstract class AdditionNode extends BinaryNode { }
abstract class MultiplicationNode extends BinaryNode { }
abstract class LiteralNode { int value; }

我们正在编写一个简单的编译器,它解析源文件并生成符合上述规范的对象层次结构.如果我们为作为访问者实现的层次结构编写解释器:

And we were writing a simple compiler which parses a source file and produces a object hierarchy that conforms to the specification above. If we were writing an interpreter for the hierarchy implemented as a Visitor:

class Interpreter implements IVisitor<int> {
  int visit(AdditionNode n) {
    int left = n.left.accept(this);
    int right = n.right.accept(this); 
    return left + right;
  }
  int visit(MultiplicationNode n) {
    int left = n.left.accept(this);
    int right = n.right.accept(this);
    return left * right;
  }
  int visit(LiteralNode n) {
    return n.value;
  }
}

转换不会让我们走得太远,因为我们不知道 visit()leftright 的类型方法.我们的解析器很可能也只返回一个 Node 类型的对象,它也指向层次结构的根,所以我们也不能安全地进行转换.所以我们的简单解释器看起来像:

Casting wouldn't get us very far, since we don't know the types of left or right in the visit() methods. Our parser would most likely also just return an object of type Node which pointed at the root of the hierarchy as well, so we can't cast that safely either. So our simple interpreter can look like:

Node program = parse(args[0]);
int result = program.accept(new Interpreter());
System.out.println("Output: " + result);

访问者模式让我们可以做一些非常强大的事情:给定一个对象层次结构,它允许我们创建在层次结构上操作的模块化操作,而无需将代码放在层次结构的类本身中.访问者模式被广泛使用,例如,在编译器构造中.给定特定程序的语法树,编写了许多对该树进行操作的访问者:类型检查、优化、机器代码发射通常都作为不同的访问者实现.在优化访问者的情况下,它甚至可以输出给定输入树的新语法树.

The visitor pattern allows us to do something very powerful: given an object hierarchy, it allows us to create modular operations that operate over the hierarchy without needing requiring to put the code in the hierarchy's class itself. The visitor pattern is used widely, for example, in compiler construction. Given the syntax tree of a particular program, many visitors are written that operate on that tree: type checking, optimizations, machine code emission are all usually implemented as different visitors. In the case of the optimization visitor, it can even output a new syntax tree given the input tree.

当然它有它的缺点:如果我们在层次结构中添加一个新类型,我们还需要为该新类型添加一个visit()方法到IVisitor代码> 界面,并在我们所有的访问者中创建存根(或完整)实现.由于上述原因,我们还需要添加 accept() 方法.如果性能对您来说意义不大,那么有一些解决方案可以在不需要 accept() 的情况下编写访问者,但它们通常涉及反射,因此会产生相当大的开销.

It has its drawbacks, of course: if we add a new type into the hierarchy, we need to also add a visit() method for that new type into the IVisitor interface, and create stub (or full) implementations in all of our visitors. We also need to add the accept() method too, for the reasons described above. If performance doesn't mean that much to you, there are solutions for writing visitors without needing the accept(), but they normally involve reflection and thus can incur quite a large overhead.

这篇关于访问者模式中accept()方法的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆