DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Design Pattern: Iterator

The Iterator pattern is used to provide a way to sequentially access elements of a collection without exposing its internal structure. It allows you to traverse lists, collections, or arrays in a simplified way. An example would be iterating over a list of items in a shopping cart without needing to know the details of how the list is implemented.

C# Code Example:

// Iterator Interface
public interface IIterator<T>
{
    bool HasNext();
    T Next();
}

// Collection Interface
public interface ICollection<T>
{
    IIterator<T> CreateIterator();
}

// Implementation of Item Collection
public class ItemCollection : ICollection<string>
{
    private List<string> _items = new List<string>();

    public void AddItem(string item)
    {
        _items.Add(item);
    }

    public IIterator<string> CreateIterator()
    {
        return new ItemIterator(this);
    }

    public List<string> GetItems()
    {
        return _items;
    }
}

// Implementation of Iterator for the Item Collection
public class ItemIterator : IIterator<string>
{
    private ItemCollection _collection;
    private int _position = 0;

    public ItemIterator(ItemCollection collection)
    {
        _collection = collection;
    }

    public bool HasNext()
    {
        return _position < _collection.GetItems().Count;
    }

    public string Next()
    {
        if (HasNext())
        {
            return _collection.GetItems()[_position++];
        }
        return null;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Create an item collection
        ItemCollection collection = new ItemCollection();
        collection.AddItem("Item 1");
        collection.AddItem("Item 2");
        collection.AddItem("Item 3");

        // Create the iterator
        IIterator<string> iterator = collection.CreateIterator();

        // Traverse the collection using the iterator
        while (iterator.HasNext())
        {
            Console.WriteLine(iterator.Next());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, the ItemCollection class implements a collection of strings and provides an iterator via the CreateIterator method. The ItemIterator implements the IIterator interface, allowing sequential traversal of the collection. In the main program, the iterator is used to access each item in the collection.

Conclusion:

The Iterator pattern allows you to traverse collections consistently without exposing the internal structure. It is useful when you want to provide a simple way to iterate over the elements of a list, set, or array.

Source code: GitHub

Top comments (0)