Tuesday 13 January 2015

Iterator Design Pattern

Iterator is one of the commonly used patterns in regular basis by most of the developers.  It  is common that most of time when we are using collections, we are using this pattern even without knowing it.

By definition the iterator pattern means that we should be able to iterate though elements of an aggregate object without exposing its underlying implementation.

Following is a basic structure of an implementation of the iterator pattern.



As we can see in this example , the client is only depending on the Interface but not with the actual implementation of the concrete class. The aggregate interface helps to create the elements of the iterator while the iterater interface used to access the elements sequentially.

The C# language implemented the Iterator pattern mainly using the IEnumerable and IEnumerator interfaces. In here the IEnumerable is used as the Aggregate interface while IEnumerator used as the Iterator interface.


The foreach loop in C# operates on any type implementing IEnumerable including basic arrays. 

Following is a very simple example.

var letters = new String[] { "a", "b", "c", "d", "e" };

            foreach(letter in letters)
                Console.WriteLine(letter);

The same can be implement using following code as well


var letters = new String[] { "a", "b", "c", "d", "e" };

            var enumerator = letters.GetEnumerator();

            while(enumerator.MoveNext())
                Console.WriteLine(enumerator.Current);

The C# LINQ is highly using this Iterator pattern.

No comments:

Post a Comment