Java Reference
In-Depth Information
public void visit(Machine m)
{
if (sought == null && m.getId() == soughtId)
{
sought = m;
}
}
public void visit(MachineComposite mc)
{
if (sought == null && mc.getId() == soughtId)
{
sought = mc;
return;
}
Iterator i = mc.getComponents().iterator();
while (sought == null && i.hasNext())
{
((MachineComponent) i.next()).accept(this);
}
}
}
The
visit()
methods frequently check the
sought
variable so that the tree traversal will
end as soon as the desired component is found.
CHALLENGE 29.2
Write a program that finds and prints out the
StarPress3404
object within
the instance of
MachineComponent
that
OozinozFactory.dublin()
returns.
Note that the
find()
method does not worry about whether the machine component it
receives as an argument is an instance of
Machine
or of
MachineComposite
.
The
find()
method simply calls
accept()
, which in turn calls
visit()
. Figure 29.4
shows this sequence of method calls.