Introduction to the Visitor Pattern
Lan Gao
[Home]    [What is it?]    [An Example]    [Resources]

What is Visitor Pattern?
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++.


An Example
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:

void Accept(Visitor *v) { v->Visit(this); }

If inst is an Instruction pointer to an If object, while sv is a Visitor pointer to a Scanner object, the code: inst->accept(sv); causes two member function calls: the first one to select If version of Accept(), and the second one within Accept() when the scanner version of Visit() is called dynamically using the base-class Visitor pointer v. Based on which concrete visitor and which instruction class are accessed, the output could be any of the following:

Scanner Output: Instruction "If"
Scanner Output: Instruction "Assign"
Scanner Output: Instruction "Repeat"
Scanner Output: Instruction "Read"
Scanner Output: Instruction "Write"
Parser Output: Instruction "If"
Parser Output: Instruction "Assign"
Parser Output: Instruction "Repeat"
Parser Output: Instruction "Read"
Parser Output: Instruction "Write"



Resources
  1. Visitor Pattern - Wikipedia
  2. Applying the visitor pattern - Thinking in C++