Iterator

Traverse the elements of a collection without exposing its internal representation.

Context

Your collection is a tree/graph/stream, and you want to allow various types of traversal (DFS, BFS) without exposing its structure.

Problem

If the client traverses the structure, it becomes coupled to its representation.

Solution

Encapsulate the traversal in an iterator that advances step by step.

#Example in C#

public class TreeNode<T>
{
    public T Value { get; set; } = default!;
    public List<TreeNode<T>> Children { get; } = new();

    public IEnumerable<T> DepthFirst()        // C# iterator with yield
    {
        yield return Value;
        foreach (var c in Children)
            foreach (var v in c.DepthFirst())
                yield return v;
    }
}

In C#, IEnumerable<T> + yield return is the Iterator pattern.

When NOT to use it

When the structure is trivial (List<T>) and foreach is already sufficient.

#behavioral #gof