Java Reference
In-Depth Information
The
next()
method checks whether a
peek
value is loaded and then checks whether it has
reported the interior node of the composite that is being traversed. If not, the
next()
method
transfers control to
next-Descendant()
.
The
nextDescendant()
method exhausts the composite beneath the current child, moving
onto the next child, if necessary:
protected Object nextDescendant()
{
while (true)
{
if (subiterator != null)
{
if (subiterator.hasNext())
{
return subiterator.next();
}
}
if (!children.hasNext())
{
return null;
}
Iterable i = (Iterable) children.next();
if (!visited.contains(i))
{
subiterator = i.iterator(visited);
}
}
}
There is a fair amount of judgment in how you design a composite iterator. A critical decision
in the design just described is that we can expect to be able to add
iterator()
methods to
the domain classes. You will have to use a different approach if you can't touch the classes
over which you want to iterate. In addition, you may find that you want to introduce other
behaviors to your composite iterators.
Suppose
that
you
decide
to
add
a
setShowInterior()
method
to
the
ComponentIterator
class. This lets you iterate over just the leaves of a composite:
package com.oozinoz.applications;
import com.oozinoz.util.*;
import com.oozinoz.process.*;
public class ShowLeavesOnly
{
public static void main(String[] args)
{
ProcessComponent pc = ShellProcess.make();
ComponentIterator i = pc.iterator();
i.setShowInterior(false);
while (i.hasNext())
{
System.out.println(i.next());
}
}
}