Java Reference
In-Depth Information
The CompositeIterator has to walk across the children of the component—
a ProcessComposite , say—over which it is iterating. The CompositeIterator class
can use a children variable to hold this iterator. Each child may be an arbitrarily deep
composite, so the Composite-Iterat or class needs a subiterator object to traverse
the component that each child represents:
package com.oozinoz.util;
import java.util.*;
public class CompositeIterator extends ComponentIterator
{
protected Iterator children;
protected ComponentIterator subiterator;
protected Object peek;
public CompositeIterator(
Object node, List components, Set visited)
{
super(node, visited);
children = components.iterator();
}
//...
}
The CompositeIterator uses a peek object to facilitate the implementation of
hasNext() . It can be difficult to tell whether a (possibly cyclic) composite has a next node.
A simple workaround is to have hasNext() search for the next value, and report whether or
not this search was successful. The CompositeIterator class employs this approach:
public boolean hasNext()
{
if (peek == null)
{
peek = next();
}
return peek != null;
}
public Object next(){
if (peek != null)
{
Object o = peek;
peek = null;
return o;
}
if (!visited.contains(node))
{
visited.add(node);
return node;
}
return nextDescendant();
}
Search WWH ::




Custom Search