The iterator mode is one of the GOF23 modes to provide traversal of the set. Why implement the iterator mode:
If an array exists, our traversal mode may be to traverse it based on indexes. Assuming that a HashTable exists, our traversal mode may traverse by key value. No matter which set they are, if their traversal does not have a public interface, then when our client calls it, it is equivalent to encoding the specific type. In this way, when the demand changes, we must modify our code. In addition, because the client code pays too much attention to the internal implementation of the Set, the Code portability will become very poor, which directly violates the open and closed principle in Object-Oriented. So the iterator model was born. Now, let's not worry about how to implement this pattern in FCL. Let's first implement our own iterator pattern.
Code List:
Public ClassProgram
{
Static VoidMain (String[] Args)
{
//Replace MyList with IMyEnumerable
IMyEnumerable list= NewMyList ();
//Get the iterator and encode the iterator in the loop, instead of the Set MyList
IMyEnumerator enumerator=List. GetEnumerator ();
For(IntI= 0; I<List. Count; I++)
{
ObjectCurrent=Enumerator. Current;
Enumerator. MoveNext ();
}
While(Enumerator. MoveNext ())
{
ObjectCurrent=Enumerator. Current;
}
}
}
/// <Summary>
///All iterators are required to implement this interface.
/// </Summary>
InterfaceIMyEnumerator
{
BoolMoveNext ();
ObjectCurrent {Get;}
}
/// <Summary>
///All sets are required to implement this interface.
///In this way, the client can encode the interface without paying attention to the specific implementation.
/// </Summary>
InterfaceIMyEnumerable
{
IMyEnumerator GetEnumerator ();
IntCount {Get;}
}
ClassMyList: IMyEnumerable
{
Object[] Items= New Object[10];
PublicIMyEnumerator MyEnumerator {Get;Set;}
Public Object This[IntI]
{
Get{ReturnItems [I];}
Set{This. Items [I]=Value ;}
}
Public IntCount
{
Get{ReturnItems. Length ;}
}
PublicIMyEnumerator GetEnumerator ()
{
If(MyEnumerator= Null)
{
Return NewMyEnumerator (This);
}
ReturnMyEnumerator;
}
}
ClassMyEnumerator: IMyEnumerator
{
IntIndex= 0;
MyList myList;