Iterator: provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.
Iterator mode structure:
Typedef String object;
Abstract class of Iterator:
Class Iterator
{
Public:
Virtual object & First () = 0;
Virtual object & Next () = 0;
Virtual bool IsDone () = 0;
Virtual object & CurrentItem () = 0;
};
// Defines the start object, obtains the next object, determines whether to end, current object, and other abstract methods, unified interface
Aggregate abstract class of Aggregate:
Class Aggregate
{
Public:
Virtual Iterator * CreateIterator () = 0; // create an Iterator
};
ConcreteIterator: a specific Iterator class that inherits Iterator
Class ConcreteIterator: public Iterator
{
Private:
ConcreteAggregate * aggregate;
List <object >:: iteratorit;
Public:
ConcreteIterator (ConcreteAggregate * aggregate)
{
This-> aggregate = aggregate;
It = aggregate-> begin ();
}
Object & First ()
{
Return * it;
}
Object & Next ()
{
Object ret = NULL;
If (++ it )! = Aggregate-> end ())
Ret = * it;
Return ret;
}
Bool IsDone ()
{
If (++ it )! = Aggregate-> end ())
Return false;
Else
Return true;
}
Object & CurrentItem ()
{
Return * it;
}
};
ConcreteAggregate: a specific aggregation class that inherits Aggregate.
Class ConcreteAggregate: public Aggregate
{
Private:
List <object> * items = new list <object> ();
Public:
Iterator * CreateIterator ()
{
Return new ConcreteIterator (ConcreteAggregate * paggregate = this );
}
Void setObject (object obj)
{
Items-> push_back (obj );
}
};
Client code:
Void main ()
{
ConcreteAggregate * pa = newConcreteAggregate ();
Pa-> setObject ("element 1 ");
Pa-> setObject ("element 2 ");
Pa-> setObject ("element 3 ");
Pa-> setObject ("element 4 ");
Iterator * it = pa-> CreateIteraor (pa );
Cout <it-> First ();
While (! It-> IsDone ())
{
Cout <it-> CurrentItem () <endl;
It-> Next ();
}
}