Visitor Pattern Jeff Schott CS590L Spring 2004
What is the Purpose of the Visitor Pattern ? n Represent an operation to be performed on the elements of an object structure n Define a new operation without changing the classes of the elements on which it operates
When do you use the Visitor Pattern? n An object structure contains many classes of objects n Many distinct and unrelated operations on these objects - want to avoid “polluting” their classes n Classes defining the object structure rarely change, but operations change frequently
Visitor Pattern Structure
Visitor Pattern Participants n Visitor n Concrete Visitor n Element n Concrete Element n Object Structure
Visitor Pattern Collaborations
Benefits of the Visitor Pattern n Makes adding new operations easy n Gathers related operations and separates unrelated operations n Visitors can visit objects that don’t have a common parent class n Visitors can accumulate state as they visit each element
Liabilities of the Visitor Pattern n Adding new Concrete Element classes is hard n Allowing a Visitor to access the internal state of a Concrete Element breaks encapsulation
Visitor Pattern Example: Compiler Syntax Tree n Operations on Syntax Tree –Type Checking –Code Generation –Pretty Printing n Different Classes for Tree Nodes –Assignment Statements –Variables –Arithmetic Expressions
Visitor Pattern Example: Node Class Hierarchy n Distributing operations across classes is confusing n Mixing operations is confusing n Adding new operations requires recompiling all classes
Visitor Pattern Example: Visitor Class Hierarchy
Visitor Pattern Example: New Node Class Hierarchy
Visitor Pattern Implementation Issues n Double Dispatch n Who is Responsible for Traversing the Object Structure? –Object Structure –Visitor –Iterator Object
Visitor Pattern Sample Code: Element
Visitor Pattern Sample Code: Visitor
Visitor Pattern Sample Code: Concrete Elements
Visitor Pattern Sample Code: Concrete Visitor
Visitor Pattern Sample Code: Concrete Visitor (cont’d)
Visitor Pattern Sample Code: Client
Visitor Pattern Known Uses n Smalltalk-80 Compiler n IRIS Inventor Toolkit n X Consortium’s Fresco Application Toolkit n Bistro Programming Language Compiler
Visitor Pattern: Related Patterns n Composite n Interpreter n Iterator
Visitor Pattern Questions?