The Iterator Design Pattern is a behavioral design pattern that provides a way to access elements of an aggregate object (e.g., a collection) sequentially without exposing the underlying representation of the object. It separates the client code from the internal structure of the collection, allowing the client to traverse the collection without needing to know its implementation details.
Here’s a C# example of the Iterator Design Pattern with a use case for iterating through a collection of items:
Create the Iterator Interface
Define an interface for the iterator, which declares methods for traversing the collection.
public interface IIterator<T>
{
T Current();
bool MoveNext();
}
Create the Aggregate Interface
Define an interface for the aggregate, which declares a method for creating an iterator.
public interface IAggregate<T>
{
IIterator<T> CreateIterator();
}
Create the Concrete Iterator
Implement the iterator interface with a concrete class that iterates through a collection. In this example, we’ll create a simple array-based iterator.
public class ArrayIterator<T> : IIterator<T>
{
private T[] _items;
private int _index = 0;
public ArrayIterator(T[] items)
{
_items = items;
}
public T Current()
{
return _items[_index];
}
public bool MoveNext()
{
_index++;
return _index < _items.Length;
}
}
Create the Concrete Aggregate
Implement the aggregate interface with a concrete class that provides the collection and creates an iterator.
public class Collection<T> : IAggregate<T>
{
private T[] _items;
public Collection(T[] items)
{
_items = items;
}
public IIterator<T> CreateIterator()
{
return new ArrayIterator<T>(_items);
}
}
Use Case – Iterating Through a Collection
Use the Iterator Design Pattern to traverse a collection of items without exposing its internal structure.
class Program
{
static void Main(string[] args)
{
string[] names = { "Alice", "Bob", "Charlie", "David" };
IAggregate<string> collection = new Collection<string>(names);
IIterator<string> iterator = collection.CreateIterator();
Console.WriteLine("Names in the collection:");
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current());
}
}
}
In this example, the Iterator Design Pattern allows you to iterate through a collection of names without exposing the details of the collection’s internal structure. The ArrayIterator
class implements the iterator interface, and the Collection
class implements the aggregate interface. This pattern is useful for providing a consistent way to traverse different types of collections while encapsulating their implementation details.