Java Reference
In-Depth Information
for a
Task
object calls the method
visitTask
on the
Visitor
. If the
Visitor
is a
CostProjectVisitor
, the
visitTask
method computes the cost associated with the
Task
.
This design offers substantial benefits. Most importantly, it is very easy to add new operations to this design. To
add a computation for time, you only have to write a new
TimeProjectVisitor
class with all of the necessary
methods to compute project time. The code for the project objects remains unchanged, since it already supports
calling the generic methods defined in the
ProjectVisitor
.
Better still, the
Visitor
provides a place to centralize state. For the
CostProjectVisitor
, you can store the
intermediate result in the
Visitor
itself while you compute the cost estimate. The centralized estimation code
also makes it easier to adjust the basic calculations. Using the Visitor pattern lets you easily add features such as
an additional weighting factor, making it easy to calculate a project discounts or, preferably, a markup.
Applicability
Use the Visitor pattern when the following conditions are met:
A system contains a group of related classes.
Several non-trivial operations need to be carried out on some or all of the related classes.
The operations must be performed differently for different classes.
Description
The Visitor pattern involves taking related operations out of a group of classes and placing them together in a
single class. The motivation is code maintainability—in some situations, it simply becomes too complicated to
maintain operations in the classes themselves. Visitor is useful for these situations, since it provides a very
generic framework to support operations on a group of classes.
The pattern requires that all classes having operations performed on them, or
Elements,
support some form of
accept method, called when the Visitor should perform an operation on the Element. The argument for that accept
method is an instance of Visitor. Each Element implementation implements the accept method to call the visit
method in the Visitor for its own class type. Every Visitor implementation implements the specific visit method
for Element subtype.
Products that might benefit from use of the Visitor pattern include those that use complex rules for configuration. As a practical example,
consider a vehicle as a purchasable product. There are dozens of decisions to make when buying a car, and many of the choices can have
an impact on things like price, financing or insurance rates.
Implementation
Figure 2.15. Visitor class diagram