cs441-f10-visitor.ppt

Download Report

Transcript cs441-f10-visitor.ppt

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
F-1
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
F-2
Uncle Bob’s Example
• Modems!
– (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?
F-3
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
F-4
Visitor Example Class Diagram
F-5
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
F-6
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)
F-7
Think about Design Tradeoffs
• Two dimensions of variability here
– They are?
• Using Visitor works best if one is more stable
than the other
– Which?
F-8
Uses of Visitor
• Hierarchical data structures
– A document structure
– A XML/HTML document
– E.g. formatting, cross-references, etc.
• Compilers
– Syntax trees
– E.g. Optimization
F-9