Explanation of Iterator Design Pattern

Explanation of Iterator Design Pattern

Hello everyone, in this article we are going to talk about iterator design pattern within Behavioral Design Patterns. We will talk about what it is and then we are going to make an example with C# language.

Let's get started.

With iterator Design patter we use the collections at efficient way. At every program we use the Collection classes like Arrays, Arraylists, Lists to keep and process some data. With iterator esign pattern we make the operation on the data within same Collection Classes.

For example: We get the all files and folders from a directory and keep all of them at the same Arraylist to make some operations on them. We can show the user on click or we can add a prefix whatever we want, we can do for this Collection. Iterator Design pattern provide us to make this operations with an efficient way.

When we use the for or foreach loops to make operations with iterations it will make it one by one. What what if we want to make this opeartions with five by five or according to dates of the records. In that case we are going to need to use Iterator Design Pattern.

Here we are going to create an iterator and we are going to use it for our items which is inside of collection.

Below image you can see the Schematic of Iterator Design Pattern Example:

Iterator Design Pattern Schematic

Now start to create our classes.

First ı will create the model class. In this example I will use a class aned Aircraft as model.

Aircraft.cs


namespace IteratorPattern_Example
{
    class Aircraft
    {
        public string Brand;
        public string Model;
        public int releaseDate;
        public bool inService;

        public Aircraft(string _brand, string _model, int _releaseDate, bool _inService)
        {
            this.Brand = _brand;
            this.Model = _model;
            this.releaseDate = _releaseDate;
            this.inService = _inService;
        }
    }
}

Now turn to We create our Interface classes.

Creating the the Interfce classes are not essential. We create it if we need to create more than one Aggregate and iterator classes. In that cases interface will make our project tidied up. So here ı created interfaces for both of them.

IAggregate.cs


namespace IteratorPattern_Example
{
    interface IAggregate
    {
        IIterator initializeIterator();
    }
}

IIterator.cs


namespace IteratorPattern_Example
{
    interface IIterator
    {
        Aircraft getNextAircraft();
        Aircraft getCurrentAircraft();
    }
}

And now we have to create our data pool class. At many place you will see this class as aggregate class. I will keep all aircraft models in this class. As you can see I derived it from Above Aggregate interface and it has a function to initialize the iterator .

This class is the collection class. We are going to keep all datas inside this Aircrafts class. You can call this class as Aggregate class as term. As you can see here we have a List and add merhod to the list. Also we have another methods to make operations on a list array like get and count.

Aircrafts.cs


using System.Collections.Generic;

namespace IteratorPattern_Example
{
    //This class is the collection class. We are going to keep all datas
    //inside this Aircrafts class. 
    //You can call this class as Aggregate class as term.
    //As you can see here we have a List and add merhod to the list.
    //Also we have another methods to make operations on a list array like get and count.
    class Aircrafts : IAggregate
    {
        List<Aircraft> aircrafts = new List<Aircraft>();
        int AircraftCount = 0;

        public void addAircraft(Aircraft _aircraft)
        {
            aircrafts.Add(_aircraft);
            //Always remember to start arrays from 0
            AircraftCount = aircrafts.Count-1;
        }

        public Aircraft getAircraft(int index)
        {
            return aircrafts[index];
        }

        public int getAircraftCount()
        {
            return AircraftCount;
        }

        public IIterator initializeIterator()
        {
            return new AircraftIterator(this);
        }
    }
}
And also I created my iterator class. Below you will see it:

With this iterator class we are going to get the datas from our data pool which we mentioned as Aggregate class named as Aircrafts class. We ill look for the datas which located inside the Aircrafts class Via Iterator class.

AircraftIterator.cs


namespace IteratorPattern_Example
{
    class AircraftIterator : IIterator
    {
        Aircrafts acs;
        int ac_index = 0;

        public AircraftIterator(Aircrafts _acs)
        {
            this.acs = _acs;
        }

        public Aircraft getCurrentAircraft()
        {
            return acs.getAircraft(ac_index);
        }

        public Aircraft getNextAircraft()
        {
            if (ac_index < acs.getAircraftCount())
            {
                ac_index++;
                return acs.getAircraft(ac_index);
            }
            else
                return null;
        }
    }
}
Our classes are ready. Now all we have to do now, initiazlie the aggregate class and through this initialize the iterator class to make some iteration for the data models which are inside of Aircrafts class.

First create our aggregate class. I created Aircrafts class for this purpose. This class will keep all Datas as you can see below.

Now we have to create our iterator here With this iterator we are going to write all datas inside the aircrafts class which is our data pool.

Program.cs


using System;

namespace IteratorPattern_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Iterator Pattern Example - Thecodeprogram";

            //First create our aggregate class.
            //I created Aircrafts class for this purpose. This class will keep all 
            //Datas as you can see below.
            Aircrafts aircrafts = new Aircrafts();
            aircrafts.addAircraft(new Aircraft("Boeing", "787", 2011, true));
            aircrafts.addAircraft(new Aircraft("Boeing", "777", 1994, true));
            aircrafts.addAircraft(new Aircraft("Boeing", "747", 1974, true));
            aircrafts.addAircraft(new Aircraft("Boeing", "737", 1948, true));
            aircrafts.addAircraft(new Aircraft("Boeing", "707", 1927, false));
            aircrafts.addAircraft(new Aircraft("Airbus", "A320", 1975, true));
            aircrafts.addAircraft(new Aircraft("Airbus", "A330", 1995, true));
            aircrafts.addAircraft(new Aircraft("Airbus", "A340", 1980, true));
            aircrafts.addAircraft(new Aircraft("Airbus", "A350", 2000, true));

            //Now we have to create our iterator here
            //With this iterator we are going to write
            //all datas inside the aircrafts class which is our data pool.
            AircraftIterator ac_iterator = new AircraftIterator(aircrafts);
            while (ac_iterator.getNextAircraft() != null)
            {
                Console.WriteLine(
                    "Model: " + ac_iterator.getCurrentAircraft().Brand +
                    " Brand: " + ac_iterator.getCurrentAircraft().Model +
                    " Release Year: " + ac_iterator.getCurrentAircraft().releaseDate +
                    " In Service?: " + ac_iterator.getCurrentAircraft().inService);
            }

            Console.ReadLine();

        }
    }
}

Output of the program will be like below image:

Iterator Design Pattern Example Program Output

That is all in this article.

You can reach the wxample application on Github via : https://github.com/thecodeprogram/IteratorPattern_Example

Have a good iteration on models.

I wish you all healthy days.

Burak Hamdi TUFAN.


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment.

Comments

  • There is no comment. Be the owner of first comment...