What is Iterator Design Pattern?

Sequentially access the elements of a collection.

The Iterator pattern provides a way of accessing elements of a collection sequentially, without knowing how the collection is structured. As an extension, the pattern allows for filtering elements in a variety of ways as they are generated.

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Design

The concept of iterators and enumerators (also called generators) has been around for a long time. Enumerators are responsible for producing the next element in a sequence defined by certain criteria. Such a sequence is said to be enumerable. Examples might be the next prime number or the next product order sorted by date. The iterator is the means by which we cycle through this sequence of elements from beginning to end.

UML Diagram

image1.gif

C# support for the pattern

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class People : IEnumerable
    {
        private Person[] _person;

        public People(Person[] person)
        {
            _person = new Person[person.Length];

            for (int i = 0; i < person.Length; i++)
                _person[i] = person[i];
        }

        public IEnumerator GetEnumerator()
        {
            foreach (Person p in _person)
                yield return p; //Yield return value to the Enumerator object.
        }
    }

       static void Main(string[] args)
      {
            Person[] peopleArray = new Person[3]
                {
            new Person(){ FirstName= "Chinna",  LastName = "Srihari"},
            new Person(){ FirstName= "Chinna",  LastName="Sushma"},
            new Person() { FirstName= "Chinna", LastName= "Lohetha"},
            };

            People p = new People(peopleArray);

            foreach (Person p1 in p)
                Console.WriteLine(p1.FirstName + ", " + p1.LastName);
 }