Applied Design Patterns with Java
Behavioral :: Visitor (331) {C ch 26}
Example - Java :: Patterns\Behavioral\Visitor
Pattern Concept: to represent an operation to be performed on the elements of an object structure. Visitor allows defining a new operation without changing the classes of the elements on which it operates. In a sense, this is a reversal of the Object-Oriented Encapsulation paradigm: Visitor creates an external class to act on data in other classes. In effect, this creates a polymorphic method that does NOT reside in a class hierarchy.
Cooper's example for the Visitor pattern considers a graphic shape hierarchy and a rendering problem:
each shape is different, yet a number of closely related functions are scattered throughout the hierarchy, resulting
in duplicated effort:
The Rose equivalent and the set of files implementing this simple 'pre-Visitor' example are below:
Instead of adding to the runtime footprint and processing time of each object, the draw() method is externalized in
a Visitor
pattern. The Visitor Drawer
instance 'visits' the objects, and calls the draw()method for those objects that accept it, as shown here:
The Rose equivalent and the set of files implementing this simple Visitor revised example are below:
The core notion in this pattern is 'visiting'. Instead of binding the needed functionality in an inheritance hierarchy, only
an accept()
method needs to be defined in the hierarchy. ALL added functionality can provided via the visit() method after the Visitor's accept() method
has been called, and the Visitor has returned itself as an argument. The visited object accesses the needed functionality
from the supplied reference:
Every object that is visited must have the following method:
public void accept(Visitor v) {
v.visit(this);
}
The Visitor pattern is appropriate when there is a need to perform an operation on data contained in a number of different objects that have different interfaces, and there is no possibility of adding a common interface to the objects.
First Example - UML : VacationDisplay
Here is Cooper's Class Diagram for the VacationDisplay application using the Visitor pattern to compute total vacation days for different types of employees, followed
by the Rose equivalent:
The UML diagram is above, and the list of Java files is below:
Second Example - UML : VacationDisplayCatchAll
Here is the Rose Class Diagram for Cooper's variation second example,
which uses a more general and extensible approach to the Visitor pattern. In this example, the previous actor of Boss was renamed to Manager, and a new Boss was derived
from it; it shows how easily a derived class can 'catch all' of the Visitor functionality:
The UML diagram is above, and the list of Java files is below:
Issues and consequences of the Visitor pattern include:
Catalog