Design Patterns Java™ Workbook

(Michael S) #1
Chapter 29. Visitor

Figure 29.4. A FindVisitor object calls a MachineComponent object's accept()
method to determine which visit() method to execute.

The short trip from the FindVisitor object to the MachineComponent object and back
again picks up the type of the MachineComponent object, ensuring that the right visit()
method of the FindVisitor class executes. This technique is called double dispatch.
The FindVisitor object dispatches a call to the MachineComponent object.
The MachineComponent object dispatches back to the visitor, calling visit() and
sending itself as an argument. This call will execute either the FindVisitor class's
visit(:Machine) method or its visit(:MachineComposite) method, depending on
the type of the machine component.


The double dispatching in VISITOR lets you create visitor classes with methods that are
specific to the various types in the visited hierarchy. As another example, consider a visitor
that finds all the machines—the leaf nodes—in a machine component.


import com.oozinoz.machine.;
import java.util.
;
public class RakeVisitor implements MachineVisitor
{
private Set leaves;
public Set getLeaves(MachineComponent mc)
{
leaves = new HashSet();
mc.accept(this);
return leaves;
}

Free download pdf