Download presentation
Presentation is loading. Please wait.
1
CS 4240 Principles of SW Design
The Visitor design pattern Readings: Shalloway and Trott Handout from Robert Martin’s book on website © 2010 T. Horton
2
The Problem You have a hierarchy of classes
Need to add a new method to carry out an action Need to define this for all classes in the hierarchy Painful, ugly, harmful, bad maintenance (some good reason) to do add a method to all classes
3
Uncle Bob’s Example Modems! A interface: Modem
(Remember modems?) A interface: Modem Classes that implement this, one for each brand or model Need a new method, say, configureForUnix() Could add it to the modem? But why not?
4
Encapsulate What Varies
Lots of possibilities for something that “does something to a modem object” depending on the object’s type Let’s call this thing a Visitor object What’s the interface between the Modem type and the Visitor type? Modem has method: accept(someVisitor) And all that does is call: someVisitor.visit(this) This implies that Visitor interface must have version of visit() for each possible Modem type
5
Visitor Example Class Diagram
6
Visitor details again Visitor interface
Has a visit(E) method for each element type E in the hierarchy of objects that can be visited Concrete classes that implement Visitor Must have version of code for every type of Element Depends on the hierarchy of elements But nice cohesion
7
Dual Dispatch and Polymorphism
Technique known as “dual dispatch” used here Two polymorphic dispatches used First: accept() is called on some object of type E (e.g. Modem) Second: then visit() is called on some object of type Visitor (which was passed)
8
Think about Design Tradeoffs
Two dimensions of variability here They are? Using Visitor works best if one is more stable than the other Which?
9
Uses of Visitor Hierarchical data structures Compilers
A document structure A XML/HTML document E.g. formatting, cross-references, etc. Compilers Syntax trees E.g. Optimization
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.