Introduction:
Sometimes you want to access a collection of objects in a sequential way without even expose how things is going inside your implementation . Iterator Design Pattern Provides you with a Skelton of how to design your classes to solve this issue.
Example:
static void Main(string[] args) { ListAggregate a = new ListAggregate(); a[0] = “Item A”; a[1] = “Item B”; a[2] = “Item C”; a[3] = “Item D”; // Create Iterator and provide aggregate ListIterator i = new ListIterator(a); Console.WriteLine(“Iterating over collection:”); string item = i.FirstItem(); while (item != null) { Console.WriteLine(item); item = i.NextItem(); } // Wait for user Console.ReadKey(); } class ListIterator : Iterator { private ListAggregate _aggregate; private int _current = 0; // Constructor public ListIterator(ListAggregate aggregate) { this._aggregate = aggregate; } // Gets first iteration item public override string FirstItem() { return (string)_aggregate[0]; } // Gets next iteration item public override string NextItem() { string ret = null; if (_current < _aggregate.Count – 1) { ret = (string)_aggregate[++_current]; } return ret; } // Gets current iteration item public override string CurrentItem() { return (string)_aggregate[_current]; } // Gets whether iterations are complete public override bool HasMoreItems() { return _current >= _aggregate.Count; } } class ListAggregate : Aggregate { private ArrayList _items = new ArrayList(); public override Iterator CreateIterator() { return new ListIterator(this); } // Gets item count public int Count { get { return _items.Count; } } // Indexer public string this[int index] { get { return (string)_items[index]; } set { _items.Insert(index, value); } } } abstract class Iterator { public abstract string FirstItem(); public abstract string NextItem(); public abstract bool HasMoreItems(); public abstract string CurrentItem(); } abstract class Aggregate { public abstract Iterator CreateIterator(); } |