1 of 7

Iterator Design Pattern �(Behavioral)

Thanh Le – Software Architect / Technical Consultant

Complexity: 1/3

Popularity: 3/3

2 of 7

Intent

  • Iterator is a behavioral design pattern that 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 in a sequential manner without knowing its internal representations.

Image source: internet

3 of 7

Problem

Collections are one of the most used data types in programming. Most collections store their elements in simple lists. However, some of them are based on stacks, trees, graphs and other complex data structures.�

Image source: internet

Various types of collections

The same collection can be traversed in different ways

4 of 7

Solution

  • The main idea of the Iterator pattern is to extract the traversal behavior of a collection into a separate object called an iterator.

  • Usually, iterators provide one primary method for fetching elements of the collection. The client can keep running this method until it doesn’t return anything, which means that the iterator has traversed all of the elements.

  • All iterators must implement the same interface. This makes the client code compatible with any collection type or any traversal algorithm as long as there’s a proper iterator. If you need a special way to traverse a collection, you just create a new iterator class, without having to change the collection or the client.

Image source: internet

5 of 7

Structure

Image source: internet

  • The Iterator interface declares the operations required for traversing a collection.

  • Concrete Iterators implement logics for traversing a collection.

  • The Collection interface declares one or multiple methods for getting iterators compatible with the collection.

  • Concrete Collections return new instances of a particular concrete iterator each time the client requests.

  • The Client works with both collections and iterators via their interfaces. This way allows you to use various collections and iterators with the same client codes.�

6 of 7

Pros/Cons

  • Single Responsibility Principle. You can clean up the client code and the collections by extracting traversal logics into separate objects.
  • Open/Closed Principle. You can implement new types of collections and iterators and pass them to existing code without breaking anything.
  • You can iterate over the same collection in parallel because each iterator object contains its own iteration state.

  • Applying the pattern can be an overkill if your app only works with simple collections.

7 of 7

Practice

https://github.com/thanhle0212/23GoF-Design-Patterns-CSharp