Iterator Pattern

Basically It belong to the group of behavioural pattern. Iterator pattern is used to iterate over collection in sequential order. The implementation shown below is modified version of Iterator pattern. In the below implementation, you will have options to go to next or choose previous Item.

Following classes will be seen in the Implementation.

1 - Interface Iterator

2 - Concrete Iterator

3 - Interface Collection

4 - Concrete Collection

-----------------------------------------------------------------------------------------

1 - Interface Iterator Class:

using System.Collections.Generic;

namespace IteratorPatternVersion1.Interface{

 public interface IIterator<T> {

       List<T> CollectionList { get; set; }

      T First { get; }

      T Next { get; }

      T Previous { get; }

      T CurrentItem { get; }

      bool IsDone { get; }

      void IncrementCounter();

      int DecrementCounter(); 

   } 

}

In the above code we have properties explained below:

a - First: Will return the first object in the collection passed.

b - Next: Will return the next object in the collection passed

c - Previous: Will return the one that comes before the current object in the collection passed.

d - CurrentItem: Will return the current object in the collection list passed

e - IsDone: Will return true if the collection is been iterated.

f - IncrementCounter(): this will increment the counter by one.

g - DecrementCounter(): This will decrement the counter by one.

----------------------------------------------------------------------------------------------------------

2 - Concrete Iterator

using IteratorPatternVersion1.Interface;

using System.Collections.Generic;

namespace IteratorPatternVersion1.ActualImplementation{

     public class ConcreteIterator<T> : IIterator<T> {

            int _counter = -1;

            public List<T> CollectionList { get; set; }

            public ConcreteIterator(List<T> collectionList)  {

            CollectionList = collectionList;

      }

      public T First  {    

            get   {   

                 _counter = 0;    

                return CollectionList[_counter];   

            }

     }

     public T Next  {    

            get  {

                 _counter++;

                 if (CollectionList != null && _counter <= CollectionList.Count - 1)    {

                     return CollectionList[_counter];    

                 }

                return default(T);   

         }

    }

    public T Previous {

        get {

                 _counter--;

                if (CollectionList != null && _counter >= 0) {

                    return CollectionList[_counter];

                 }     

                  return default(T);    

        }

    }

    public T CurrentItem  {

            get {

                if (CollectionList != null && _counter <= CollectionList.Count - 1) {

                  return CollectionList[_counter];

             }

             return default(T);

          }

    }

   public bool IsDone  {

        get   {

             return _counter >= CollectionList.Count - 1;

        }

    }

    public void IncrementCounter()  {

        _counter++;

    }

    public void DecrementCounter()  {

        _counter--;

        }

    }

}

In the above code we have inherited from IInterator class.

The constructor of this class will have the collection on which we need to iterator.

----------------------------------------------------------------------------------------------

3 - Interface Collection

using System.Collections.Generic;

namespace IteratorPatternVersion1.Interface{

    public interface ICollectionList<T> {

          List<T> CollectionLists { get; set; }

          IIterator<T> CreateIterator();

     }

}

We will discuss about the property and methods in the implementation class.

------------------------------------------------------------------------------------

4 - Concrete Collection

using IteratorPatternVersion1.Interface;

using System.Collections.Generic;

namespace IteratorPatternVersion1.ActualImplementation{

        public class CollectionList<T> : ICollectionList<T> {

              public List<T> CollectionLists { get; set; }

              public CollectionList(List<T> collectionLists)  {

                       CollectionLists = collectionLists;

              }

              public IIterator<T> CreateIterator()  {

                       return new ConcreteIterator<T>(CollectionLists);

              }

        }

}

In the above concrete collection. We need the list of objects that need to be iterated.

Now in order for the list to be iterated, we have to create the iterator object from within the class. Thus under CreateIterator Method, we create the object of ConcreteIterator and given the List that we got int constructor.

------------------------------------------------------------------------------------------

Create Scenario to User Iterator

In the above implementation, we have successfully created a generic Iterator that needs List<T> to iterate over.

In order to test this we will simply create a object List and iterate over the List.

-------------------------------------------------------------------------------------------

5 - Simple Object Person

namespace IteratorPatternVersion1.ActualImplementation{

         public class Person {

              public int Age { get; set; }

              public string Name { get; set; }

         }

}

this is simple class with two properties.

---------------------------------------------------------------------------------------

The main program that uses this object is given below.

using IteratorPatternVersion1.ActualImplementation;

using IteratorPatternVersion1.Interface;

using System;

using System.Collections.Generic;

namespace IteratorPatternVersion1{

         class Program {

                static void Main(string[] args)  {

                            ICollectionList<Person> collectionList = new CollectionList<Person>(CreateCollectionList());

                           IIterator<Person> iteratorPerson = collectionList.CreateIterator();    

                           int count = 1;

                           while (!iteratorPerson.IsDone)   {

                                Person person = iteratorPerson.Next;

                                Console.WriteLine("Person Number : " + count);

                                Console.WriteLine("Age: " + person.Age);

                                Console.WriteLine("Name: " + person.Name);

                                count++;

                           }

                           Console.ReadLine();

                           

                            Console.WriteLine("-------------First------------");

                           Person personFirst = iteratorPerson.First;

                           Console.WriteLine("Age: " + personFirst.Age);

                           Console.WriteLine("Name: " + personFirst.Name);

                           Console.ReadLine();

                           

                            Console.WriteLine("-------------Next------------");                        

                            Person personNext = iteratorPerson.Next;

                           Console.WriteLine("Age: " + personNext.Age);

                           Console.WriteLine("Name: " + personNext.Name);

                           Console.ReadLine();

                        

                           Console.WriteLine("-------------Step Previous------------");    

                            iteratorPerson.DecrementCounter();

                           Person personPrevious = iteratorPerson.CurrentItem;

                           Console.WriteLine("Age: " + personPrevious.Age);

                           Console.WriteLine("Name: " + personPrevious.Name);

                          Console.ReadLine();


                           Console.WriteLine("-------------Step Next------------");

                           iteratorPerson.IncrementCounter();

                           Person personNextItem = iteratorPerson.CurrentItem;

                           Console.WriteLine("Age: " + personNextItem.Age);

                           Console.WriteLine("Name: " + personNextItem.Name);

                           Console.ReadLine();

        }

  static List<Person> CreateCollectionList()  {

            return new List<Person>()   {

                    new Person{ Age=12,Name="ABC"},

                    new Person{ Age=13,Name="DEF"},

                    new Person{ Age=14,Name="GHI"},

                    new Person{ Age=15,Name="JKL"},

                    new Person{ Age=16,Name="MNO"},

                    new Person{ Age=17,Name="PQR"}

           };

      }

   }

}



Comments

Popular posts from this blog

Upgrading from Sitecore 9.3 to 10.3: A Practical Guide

Rebuild XDB indexing Issues

Optimizing Data Extraction from XDB in Sitecore: A Comprehensive Guide to Efficient Report Generation