Iterator

GoF Definition

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Many times your code will need to deal with a collection of objects. You are probably aware that the System. Collections and System.Collections.Generic namespaces provide many classes that represent a collection of objects. An ArrayList , List , and Dictionary are some of them.

Iterating through a collection of object is quite common in .NET applications. In C# the foreach loops

simplify the overall access to the individual elements of a collection.

In many cases the built-in collection classes serve the purpose of iterating and accessing a collection

sequentially quite well. However, in some cases you may want to devise your own way to iterate through a collection.

The iterator pattern allows your code to access the individual elements of an aggregate object sequentially. In doing so, the client is shielded from knowing the internal details of the aggregate object.

This concept is used frequently to traverse the nodes of a tree-like structure. So, in many scenarios, you may notice the use of the Iterator pattern with the Composite pattern.

Suppose you have some data stored as a JSON file. The client wants to read and access the data—it must know how the JSON file is structured. The Iterator pattern can separate that logic away from the client and provide a simplified, cursor-like way to iterate through the JSON file.

The IIterator interface defines the abstraction for the iterator. It has methods such as First() , Next() ,

Current() , and IsDone() .

The Iterator class implements IIterator and provides the concrete implementation for the methods

just mentioned.

The Iterator object simply iterates through an Aggregate.

The actual collection is represented by the IAggregate interface.

The CreateIterator() method of the IAggregate interface, when implemented, is supposed to return an Iterator object for iterating through the aggregate.

The Aggregate class implements the IAggregate interface and represents the collection of elements to be iterated upon.