Introduction to the Visitor Pattern Lan Gao |
[Home] [What is it?] [An Example] [Resources] |
The "visitor" design pattern is a way of separating an algorithm
from an object structure. The basic idea is that you have a set of
element classes that form an object structure. Each of these element
classes has an "accept" method that takes a visitor object as an
argument. The visitor is an interface that has a different "visit"
method for each element class. The "accept" method of an element class
calls back the "visit" method for its class. Separate concrete visitor
classes can then be written that perform some particular operations.
You can think of these visit methods as methods not of a single class, but rather methods of a pair of classes: the concrete visitor and the particular element class. Thus the visitor pattern simulates double dispatch in a conventional single dispatch object-oriented language such as Java or C++. |
As a simple illustration example, the instruction visitor package can
be downloaded here.
In this example, we have five concrete Instruction classes (If, Assign,
Repeat, Read, and Write). Each of these classes has an "Accept" method
that takes a Visitor object as an argument. On the other hand, the
Visitor class has five different "Visit" methods, one for each
Instruction class. There are two concrete Visitor classes (Scanner and
Parser) that can be written to perform some particular operations.
The "Accept" method of an Instruction class calls back the "Visit" method for its class like this:
If inst is an Instruction pointer to an If
object, while sv is a Visitor pointer to a Scanner
object, the code:
|