Professional Documents
Culture Documents
3/3/2018
John Roberts
2
Overview
• Visitor Design Pattern
• Double Dispatching
• Implementation
3
Context
• Print it
• etc.
4
Assumptions
5
Assumptions
6
Approach
• If the node accepts the visitor, then the node calls on the
visitor to visit the node’s tree, and process
7
Example (from ProgramTree)
package ast;
import visitor.*;
public ProgramTree() {
}
8
Example (from ProgramTree)
9
Example
tree.accept( visitor );
10
Example
11 We actually use a modified form, where the concrete visitors (and interface)
Visitor Design Pattern specify a visit method for each AST type…
<<interface>> <<interface>>
Element Visitor
+ visit( e : ElementOne )
+ visit( e : ElementTwo )
ElementOne ElementTwo
+ accept( v : Visitor ) + accept( v : Visitor )
ConcreteVisitor
+ visit( e : ElementOne )
v.visit( this ) + visit( e : ElementTwo )
12
Overview
• Visitor Design Pattern
• Double Dispatching
• Implementation
13
Apparent Type
14
Actual type
15
Apparent and Actual Types
• The Java compiler determines what calls are legal based on the
object’s apparent type
17
Dispatching
18
Dispatching
20
Dispatching
nodeNum
23
Dispatching
• This results from the fact that visitor’s actual type is not
determinable until runtime, so we don’t know what
visitProgramTree method will execute until runtime
24
Overview
• Visitor Design Pattern
• Double Dispatching
• Implementation
25
Double Dispatch
• No switch!
26
Wherein we malign switch
27
Dynamic Binding
29
Double Dispatch
30
Double Dispatch
tree.accept( visitor );
ProgramTree.accept( visitor );
visitor.visitProgramTree( this );
31
Double Dispatch
tree.accept( visitor );
ProgramTree.accept( visitor );
visitor.visitProgramTree( this );
32
Overview
• Visitor Design Pattern
• Double Dispatching
• Implementation
33
Implementation
• ASTVisitor.java
• PrintVisitor.java
• Compiler.java