// Returns the key of the current element publicabstractintKey();
// Returns the current element publicabstractobjectCurrent();
// Move forward to next element publicabstractboolMoveNext();
// Rewinds the Iterator to the first element publicabstractvoidReset(); }
abstractclassIteratorAggregate : IEnumerable { // Returns an Iterator or another IteratorAggregate for the implementing // object. publicabstract IEnumerator GetEnumerator(); }
// Concrete Iterators implement various traversal algorithms. These classes // store the current traversal position at all times. classAlphabeticalOrderIterator : Iterator { private WordsCollection _collection;
// Stores the current traversal position. An iterator may have a lot of // other fields for storing iteration state, especially when it is // supposed to work with a particular kind of collection. privateint _position = -1;
// Concrete Collections provide one or several methods for retrieving fresh // iterator instances, compatible with the collection class. classWordsCollection : IteratorAggregate { List<string> _collection = new List<string>();
classProgram { staticvoidMain(string[] args) { // The client code may or may not know about the Concrete Iterator // or Collection classes, depending on the level of indirection you // want to keep in your program. var collection = new WordsCollection(); collection.AddItem("First"); collection.AddItem("Second"); collection.AddItem("Third");
Console.WriteLine("Straight traversal:");
foreach (var element in collection) { Console.WriteLine(element); }
Console.WriteLine("\nReverse traversal:");
collection.ReverseDirection();
foreach (var element in collection) { Console.WriteLine(element); } } } }