-
The Iterator Design Pattern allows sequential access to elements without exposing the inside logic. That means using the Iterator Design Pattern, we can access the elements of a collection sequentially without knowing its internal representations.
-
Iterator pattern falls under behavioral pattern category.
-
Suppose we have a collection of employees. Then, we can easily iterate through the collection using either for or for each loop in C#, as shown in the below code.
-
Here, the for-each loop sequentially accesses the elements from the collection without exposing the internal logic, i.e., how it is accessing the elements sequentially. Again, you need to change the client code to use a different data structure. Is it not nice to provide a uniform interface for traversing different collections?
-
For example, your application may have different types of collections, such as List, Array, ArrayList, Generic Dictionary, etc. For whichever type of collection you have, you will need to traverse or iterate through the elements of the collections sequentially. The actual implementation of how to traverse different types of collections will be different, yet the client code should not be concerned about the details of the implementations. The Iterator Design Pattern helps you to hide such details and provides a generic interface for the client to traverse different types of collections, as shown in the image below.