Software-Entwurfsmuster

Compound iterator implementation

The compound iterator follows the bridge design pattern. It uses a behavior that contains the base iterator, the subiterator, and the function composeItems. Furthermore, the behavior contains a factory method for creating the so-specified compound iterator.

Abstract class CompoundIteratorBehavior

Any behavior of a compound iterator extends the abstract class CompoundIteratorBehavior that requires methods baseIterator, subIterator and composeItems. Furthermore, the class CompoundIteratorBehavior contains the factory method iterator that creates the so-specified compound iterator.

public abstract class CompoundIteratorBehavior<BaseTypeSubTypeCompoundType>
{
    // the base iterator
    public abstract Iterator<BaseType> baseIterator();

    // the subiterator
    // x0 is the cursor object of the base iterator
    public abstract Iterator<SubType> subIterator(BaseType x0);

    // specifies the object composed of the two cursor objects x0 and x1
    public abstract CompoundType composeItems(BaseType x0, SubType x1);

    // factory method that creates the compound iterator
    public Iterator<CompoundType> iterator()
    {
        return new CompoundIterator<BaseTypeSubTypeCompoundType>(this);
    }

}

Class CompoundIterator

In the following, the implementation of the compound iterator is given.

public class CompoundIterator<BaseTypeSubTypeCompoundType>
implements Iterator<CompoundType>
{
    private CompoundIteratorBehavior<BaseTypeSubTypeCompoundType> behavior;
    private boolean hasnext;
    private Iterator<BaseType> it0;
    private Iterator<SubType> it1;
    private BaseType x0;
    private CompoundType x01;

    public CompoundIterator(CompoundIteratorBehavior<BaseTypeSubTypeCompoundType> behavior)
    {
        this.behavior=behavior;
        hasnext=true;
        it0=behavior.baseIterator();
        x01=tryNext0();
    }

    public boolean hasNext()
    {
        return hasnext;
    }

    public CompoundType next()
    {
        CompoundType x=x01;
        x01=tryNext1();
        return x;
    }

    private CompoundType tryNext0()
    {
        while (it0.hasNext())
        {
            x0=it0.next();
            if (x0!=null)
            {
                it1=behavior.subIterator(x0);
                return tryNext1();
            }
        }
        hasnext=false;
        return null;
    }

    private CompoundType tryNext1()
    {
        if (it1.hasNext())
            return behavior.composeItems(x0, it1.next());
        else
            return tryNext0();
    }

}

 

 

Next:  [Usage of the compound iterator]   or   [up]

 


H.W. Lang   mail@hwlang.de   Impressum   Datenschutz
Created: 05.02.2008   Updated: 18.02.2023