Iterator: Introduction
Get a brief introduction to the Iterator design pattern.
We'll cover the following
The Iterator design pattern allows a developer to encapsulate a collection of any complexity inside an object with a very simple interface. The consumers of this interface can iterate through each individual item of this collection without knowing any of its implementation details.
In C#, pretty much any built-in collection data types traversed inside a for each
loop are based on the Iterator design pattern. For example, they expose methods, such as the MoveNext()
method, which are commonly used by this design pattern.
Summarized concept of the Iterator design pattern
The Iterator design pattern can be summarized as follows:
- There’s an object known either as an Aggregate or a Collection. This object stores the actual collection of objects. This collection can be of any structure and complexity (trees, stacks, arrays, etc.).
- There’s an object called the Iterator object, which reads the items from the Aggregate object and exposes them to the outside world one by one.
- The Iterator object reads items in a specific order and keeps track of the current item.
Get hands-on with 1400+ tech skills courses.