A Few Notes on the Visitor Pattern
- Useful when the inheritance hierarchy is relatively stable, but the
operations are not (eg. compilers).
- Suppose we have a system for dealing with simple expressions with
operations TypeCheck and PrettyPrint (see the diagram
below).
- Now suppose we want to add an operation (like CodeGen). To do
so, we will have to modify each sub-class of Expression.
- The visitor pattern addresses this problem by defining an abstract class
with an abstract operation for each sub-class of the class to be visited.
- Each operation to be defined on the original class is now defined as a
sub-class of the visitor class. In the class diagram below, the TypeCheck
sub-class of the ExpressionVisitor class now implements all of the
type checking code that was spread across the different sub-classes of
Expression in the original diagram (and similarly for PrettyPrint).
- To make the connection to the class being visitied, each sub-class of
the original class is given a new operation, accept, that is passed a
visitor object. The sub-class then calls the operation in the visitor
class for dealing with its type on itself.
- Adding a new operation now only requires defining a new sub-class of the
visitor class and does not require any modification to the original class
definition.
- For the example, we would just add a new class, CodeGen, as a
subclass of ExpressionVisitor.
Notes
- If we add a new sub-class to Expression, we have to modify each
sub-class of ExpressionVisitor. Make sure your class diagram is
stable before using the visitor pattern.
- As defined, the visitor operations consume no input and produce no
output so all effects must be seen through some external artifact (global
variables, databases, or some such). A better solution is to parameterize
the visitor class on input and output types (see the list example).
References
- Design Patterns - Gamma, Helm, Johnson, & Vlissides.
Addison-Wesley 1995 (ISBN 0-201-63361-2). Classic book, the definitive book
on patterns. Great as a reference but perhaps such a good tutorial.
- A Little Java, A Few Patterns - Felleisen & Friedman. MIT Press
1998 (ISBN 0-262-56115-8). Nice little book illustrating some of the design
patterns in a light-hearted manner. Prose tries to be humorous and
disarming but is not to everyone's taste.