The Rundown

The Participants

The Iterator defines an interface for accessing an Aggregate object and traversing elements within that Aggregate.

The ConcreteIterator implements the Iterator interface and keeps track of its current position within the Aggregate.

The Aggregate defines an interface for creating an Iterator object.

The ConcreteAggregate implements the Iterator creation interface and returns a ConcreteIterator for that ConcreteAggregate.

A Delicious Example

To demo how we might use the Iterator design pattern, let's talk about my favorite sugary snack: jelly beans. So far as I am concerned, these little nuggets of sugar and flavor are the best thing since sliced bread.

Notice that the ConcreteAggregate needs to implement methods by which we can manipulate objects within the collection, without exposing the collection itself. This is how it can fit with the Iterator design pattern.

Finally, in our Main(), we can create a collection of jelly beans and then iterate over them:

Will I Ever Use This Pattern?

Absolutely. The pattern is astonishingly useful when attempting to retrieve objects from collections that you'd rather not expose to outside usage (because that's, like, the pattern's entire purpose). If you primarily work in the ASP.NET world (as I do) and you use LINQ, you are already using the Iterator pattern extensively (e.g. collection.First() or collection.Count()).

Summary

The Iterator pattern provides a manner in which we can access and manipulate objects in a collection without exposing the collection itself. This pattern is incredibly common and incredibly useful, so keep it in mind; once you know what it is, you'll start seeing it everywhere.

As always, I like to provide code with my tutorials, so the repository for this pattern is over on GitHub and contains all of the sample code used here.

Aaaaand now I need some sugar. The literal kind. Gimme all the jelly beans!