Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

java - How does double dispatch work in Visitor pattern?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Single-dispatch

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

Nodes Visitors

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...