Download presentation
Presentation is loading. Please wait.
1
Visitor Pattern Jeff Schott CS590L Spring 2004
2
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
3
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
4
Visitor Pattern Structure
5
Visitor Pattern Participants n Visitor n Concrete Visitor n Element n Concrete Element n Object Structure
6
Visitor Pattern Collaborations
7
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
8
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
9
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
10
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
11
Visitor Pattern Example: Visitor Class Hierarchy
12
Visitor Pattern Example: New Node Class Hierarchy
13
Visitor Pattern Implementation Issues n Double Dispatch n Who is Responsible for Traversing the Object Structure? –Object Structure –Visitor –Iterator Object
14
Visitor Pattern Sample Code: Element
15
Visitor Pattern Sample Code: Visitor
16
Visitor Pattern Sample Code: Concrete Elements
17
Visitor Pattern Sample Code: Concrete Visitor
18
Visitor Pattern Sample Code: Concrete Visitor (cont’d)
19
Visitor Pattern Sample Code: Client
20
Visitor Pattern Known Uses n Smalltalk-80 Compiler n IRIS Inventor Toolkit n X Consortium’s Fresco Application Toolkit n Bistro Programming Language Compiler
21
Visitor Pattern: Related Patterns n Composite n Interpreter n Iterator
22
Visitor Pattern Questions?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.