CS 4240 Principles of SW Design The Visitor design pattern Readings: Shalloway and Trott Handout from Robert Martin’s book on website www.oodesign.com © 2010 T. Horton
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
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?
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
Visitor Example Class Diagram
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
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)
Think about Design Tradeoffs Two dimensions of variability here They are? Using Visitor works best if one is more stable than the other Which?
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