问题描述
我正在研究与访客模式有关的其他问题,但不了解访客模式的双重调度.
请参考链接 访客模式
双重调度如何在访问者模式中工作?
推荐答案
元素对象的accept方法接收访问者对象,并在访问者对象上调用visit方法.由于访问者对象具有多种visit方法,因此基于元素类型,称为适当的visit方法.在这里,我们有两个呼叫( double dispatch ),它们指定了元素和右操作(基于其类型).
其他推荐答案
单dispatch
假设节点是接口类,两个子类是接口的具体实现.
如果您在节点实例上调用GenerateCode()方法,则执行的实际操作取决于节点的 type .它可以是VariableRefNode或AssignmentNode中的方法.如果您致电PrettyPrint(),也是一样的.因此,执行的实际操作取决于您正在调用的方法的名称和节点的类型.
double-dispatch
这次Node允许您将类型NodeVisitor的参数传递给其称为Accept的方法.在您的程序中,如果您在节点实例上调用Accept,则实际执行的实际操作取决于节点的类型(VariableRefNode或AssignmentNode)和您传递到Accept的访问者实例的类型(TypeCheckingVisitor或CodeGeneratingVisitor).
其他推荐答案
好吧,这是该文章的相关报价:
访客实施"双重调度". OO消息通常表现出"单个调度" - 执行的操作取决于:请求的名称和接收器的类型.在"双重调度"中,执行的操作取决于:请求的名称和两个接收器的类型(访问者的类型和访问的元素类型).
这本质上意味着不同的访问者可以访问相同的类型,并且同一访问者可以访问不同的类型.使用访问者模式执行的指定操作的效果可能取决于访问者和访问者(double Dispatch).
问题描述
I was looking into other questions related to the visitor pattern but couldn't understand the implementation of double dispatch in visitor pattern.
Please refer to the link Visitor Pattern
How does double dispatch work in the Visitor pattern?
推荐答案
The element object's accept method receives a visitor object and it calls the visit method on the visitor object. As the visitor object has several visit methods, based on the element type the appropriate visit method is called. Here we have two calls (double dispatch) that specify the element and the right operation for the element (based on its type).
其他推荐答案
Single-dispatch
Assume Node is an interface class and the two sub classes are concrete implementations of the interface.
If you call GenerateCode() method on a node instance, the actual operation getting executed depends on the type of the node. It could be the method either in VariableRefNode or AssignmentNode. It's the same if you call PrettyPrint(). So the actual operation getting executed depends on name of the method you are calling and the type of the node.
Double-dispatch
This time the Node is allowing you to pass a parameter of type NodeVisitor to its method called Accept. In your program if you call Accept on a node instance, the actual operation getting executed now depends on the type of the node (VariableRefNode or AssignmentNode) AND the type of the visitor instance you passed into Accept (TypeCheckingVisitor or CodeGeneratingVisitor).
其他推荐答案
Well, here's the relevant quote from that article:
Visitor implements “double dispatch”. OO messages routinely manifest “single dispatch” - the operation that is executed depends on: the name of the request, and the type of the receiver. In “double dispatch”, the operation executed depends on: the name of the request, and the type of TWO receivers (the type of the Visitor and the type of the element it visits).
This essentially means different visitors can visit the same type and different types can be visited by the same visitor. The effect of a named operation that is performed using the visitor pattern may depend on the visitor and the visited (double dispatch).