The visitor pattern is a design pattern that allows adding new operations to classes without changing them. In this document, we explore the use of the visitor pattern for expression trees, where we define two class hierarchies: one for the elements being operated on and one for the visitors that define operations on the elements. Each object structure, such as an expression tree, will have an associated visitor class, and the visitor will define visit operations for each concrete class. The visitor will traverse the structure and perform the desired operation on each element. The visitor pattern achieves this by using a technique called double-dispatch, where the operation used to fulfill a request is determined by the name of the request and the types of both the receiver and the visitor.
Download Visitor Pattern for Expression Trees: Adding Operations Without Modifying Existing Code and more Papers Computer Science in PDF only on Docsity!
Software Design
CSE 335, Spring 2006
Visitors
Stephen Wagner
Michigan State University
Visitors
Suppose we have a complicated expression tree:
add, subtract, multiply
literals, variables, arrays
min, max, arbitrary functions
control logic
We can perform several operations
evaluate
type check
simplify
Visitors
With the visitor pattern you define two class hierarchies
one for the elements being operated on (e.g. the expression nodes)
one for the visitors that define operations on the elements
You create a new operation by adding a new class to the visitor class hierarchy
This will require writing lots of code
However we do not have to modify the expression node hierarchy