Iterator mode:
Provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.
In C #/Java, foreach is used by the iterator.
. Net
Ieumerator supports simple iterative interfaces for non-generic sets.
For example, foreach (string I in Str) {print I}
That is:
Ienumerator <string> E = Str. getenumerator ();
While (E. movenext ())
{
Printe. Current;
}
Demo:
//Iterator abstract class
Abstract class iterator
{
Public abstract object first ();
Public abstract object next ();
Public abstract bool isdone ();
Public abstract object currentitem ();
}
// Specific iterator
Class concreteiterator: iterator
{
Private concreteaggregate aggregate;
Private int current = 0;
Public concreteiterator (concreteaggregate aggregate)
{
This. Aggregate = aggregate;
}
Public override object first ()
{
Return aggregate;
}
Public override object next ()
{
Object ret = NULL;
Current ++;
If (current <aggregate. Count)
{
Ret = aggregate [current];
}
Return ret;
}
Public override bool isdone ()
{
Return Current> = aggregate. Count? True: false;
}
Public override object currentitem ()
{
Return aggregate [current];
}
}
//Aggregation abstract class
Abstract class Aggregate
{
Public abstract iterator createiterator ();
}
// Specific clustering class
Class concreteaggregate: Aggregate
{
Private ilist <Object> items = new list <Object> ();
Public override iterator createiterator ()
{
Return new concreteiterator (this );
}
Public int count // returns the total number of aggregates.
{
Get {return items. Count ;}
}
Publicobject this [int Index] // declare an Indexer
{
Get {return items [Index];}
Set {items. insert (index, value );}
}
}
Class Program
{
Static void main (string [] ARGs)
{
Concreteaggregate A = new concreteaggregate ();
A [0] = "laruence ";
A [1] = "laruence 1 ";
A [2] = "laruence 2 ";
A [3] = "laruence 3 ";
Iterator I = new concreteiterator ();
// Object ittem = I. First ();
While (! I. isdone ())
{
Console. writeline ("{0} buy a ticket. ", I. currentitem ());
I. Next ();
}
Console. readkey ();
}
}