Iterator Design Pattern Using C#

Iterator design pattern is one of the behavioral design patterns. It is applicable to the situation when a collection of objects has to be iterated without exposing its internal structure. The whole intent is that it is of less importance how collection has been internally stored from user point of view. The user is only concerned how he/she can access a collection. Using the word “access” is a little ambiguous in this context therefore it needs more clarity.

When accessing a collection, a user can iterate over a collection in a forward or backward manner or randomly. In forward manner, starting from Zero (0) user can access collection till end and in backward manner, it’s vice versa. User can also attempt to access the items of a collection randomly. That means accessing a collection has got different meanings.

Problem Description

An online shop sells clothes. The shop does not own clothes. However, it sells clothes from various stores and it charges a brokerage on the number of clothes sold e.g. ebay. Brokerage is not important for us in this example. Therefore, we shall not talk about it in detail. Every store has got a different meaning of providing their collection of clothes to online shop interface.

Let’s say we have two stores, EspiritStore and ZaraStore. EspiritStore stores its clothes in a List collection whereas ZaraStore in an Array. Both stores implement an interface and returns an IEnumerable collection of type Clothes. Problem at the client end is that it needs two functions to iterate over the collection separately. For EspiritStore, it iterates over a List whereas for ZaraStore over an Array.

Well, at the outset, it is not important for stores to expose how their elements are internally stored. Online Shop should only be concerned to iterate over a collection without having to know their internal structure e.g. Array, List or Dictionary etc.

Solution

From online shop point of view, it is only concerned about if a collection has items and if that’s the case, it should be able to access them. In principle, every store should provide an iterator that should implement an interface with the following two methods:

  1. public interface ITerator{  
  2.    bool hasNext();  
  3.    object Next();  
  4. }  
Advantage of following this approach is that stores instead of returning access to their internal data structure can return Iterators and encapsulate whole accessing of their data structures in their respective iterators.

An example of the approach has been shown below:

hasNext() method should check if element has got items in the collection based on a incrementing position number.

Next() method returns an Object from collection which can be later casted to an expected type.
  1. public class EspiritStoreIterator : ITerator  
  2. {  
  3.     private readonly List<Item> _listOfItems;  
  4.   
  5.     private int Position = 0;  
  6.   
  7.     public EspiritStoreIterator(List<Item> listOfItems)  
  8.     {  
  9.         _listOfItems = listOfItems;  
  10.     }  
  11.   
  12.     public bool hasNext()  
  13.     {  
  14.         if  (Position>_listOfItems.Count-1)  
  15.             return false;  
  16.         return !_listOfItems.ElementAt(Position).Equals(null);  
  17.   
  18.     }  
  19.   
  20.     public object Next()  
  21.     {  
  22.         return _listOfItems.ElementAt(Position++);  
  23.     }  
  24. }  
Each store creates and returns an iterator to the client therefore no longer exposes the whole data structure.
  1. public class EspiritStore : VirtualStore  
  2. {  
  3.    //list of items  
  4.     readonly List<Item>  _listOfItems= new List<Item>();  
  5.   
  6.    public override void AddItemsInStore()  
  7.    {  
  8.     addItemsInStore();      
  9.    }  
  10.   
  11.    private void addItemsInStore()  
  12.    {  
  13.        _listOfItems.Add(new Item() {Name = "Shirt", Description = "Sommer", Price = 20, Size = 40});  
  14.        _listOfItems.Add(new Item() { Name = "Hose", Description = "winter", Price = 50, Size = 45 });  
  15.    }  
  16.   
  17.     //public override IEnumerable<Item> GetItems()  
  18.     //{  
  19.     //    return _listOfItems;  
  20.     //}  
  21.   
  22.    public ITerator CreateIterator()  
  23.    {  
  24.        return new EspiritStoreIterator(_listOfItems);  
  25.    }  
  26. }  
Now with the current implementation, it becomes easy for client (online shop) to access an iterator given a store type (shown below):
  1. internal class OnlineWindow  
  2. {  
  3.     private readonly EspiritStore _espiritStore;  
  4.     private readonly ZaraStore _zaraStore;  
  5.   
  6.     public OnlineWindow(EspiritStore espiritStore, ZaraStore zaraStore)  
  7.     {  
  8.         _espiritStore = espiritStore;  
  9.         _zaraStore = zaraStore;  
  10.     }  
  11.   
  12.   
  13.     public void PopulateWindow()  
  14.     {  
  15.         Console.WriteLine("Items from Espirit Store\n");  
  16.         ITerator iTerator = _espiritStore.CreateIterator();  
  17.   
  18.         Console.WriteLine("Items from Espirit Store\n");  
  19.         PrintStoreItems(iTerator);  
  20.   
  21.         iTerator = _zaraStore.CreateIterator();  
  22.   
  23.   
  24.         Console.WriteLine("\n");  
  25.         Console.WriteLine("Items from Zara Store\n");  
  26.         PrintStoreItems(iTerator);  
  27.     }  
  28.   
  29.     private void PrintStoreItems(ITerator iTerator)  
  30.     {  
  31.         while (iTerator.hasNext())  
  32.         {  
  33.             Console.WriteLine((Item) iTerator.Next());  
  34.         }  
  35.     }  
  36. }  
PopulateWindow() access iterators of stores through CreateIterator() method and pass them to PrintStoreItems method to print them. Now Online Shop does not need two methods separately to print each store items.

In my example, I have created my own Iterator but almost in all language these iterators are provided by their own framework. In Java, this feature is supported by Iterator Interface, whereas .NET provides IEnumerable Interface.

Now that we have seen an Iterator, let’s define different players in the pattern.

Class daigram

Participants
  • Iterator: An abstract class how elements of a collection can be accessed.

  • ConcreteIterator: ZaraStoreIterator and EspiritStoreIterator are the concreate iterators implement Abstract Iterator. They also hold the current Position of the tracked item in the collection.

  • Aggregate: An abstract class which each store should implement and provide implementation of CreateIterator method.

  • ConcreteAggregate: EspiritStore and ZaraStore are concrete classes playing role of an aggregate. They create concrete aggregate holding the collection and providing homogenous access and traversal to items in the collection.

A concrete Iterator keeps track of the current item in the aggregate and can return the next item in the aggregated collection.

As stated above, .NET framework also provides IEnumerable iterator interface. I have provided implementation using IEnumerable interface in the project attached. I suggest readers to have a look on that to understand the interface better.

So as to summarize, Iterators are widely used in Object Oriented Programming. Almost all collection classes offer iterators in one or other form. To know more about iterators, refer to MSDN.