What is the Iterator Design Pattern?
The Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object (like a list) sequentially without exposing its underlying representation. It defines a separate object, called an iterator, which encapsulates the details of traversing the elements of the aggregate, allowing the aggregate to change its internal structure without affecting the way its elements are accessed.
- Iterator Pattern is a relatively simple and frequently used design pattern. There are a lot of data structures/collections available in every language.
- Each collection must provide an iterator that lets it iterate through its objects. However, while doing so it should make sure that it does not expose its implementation.
Suppose we are building an application that requires us to maintain a list of notifications. Eventually, some parts of your code will require you to iterate over all notifications. If we implemented your collection of notifications as an array you would iterate over them as:
// If a simple array is used to store notifications
for (int i = 0; i < notificationList.length; i++)
Notification notification = notificationList[i]);
And if it were some other collection like set, tree, etc. way of iterating would change slightly. Now, what if we build an iterator that provides a generic way of iterating over a collection independent of its type.
// Create an iterator
Iterator iterator = notificationList.createIterator();
// It wouldn’t matter if list is Array or ArrayList or
// anything else.
while (iterator.hasNext())
{
Notification notification = iterator.next());
}
Iterator Design Pattern
The Iterator pattern is a widely used design pattern in software development that provides a way to access the elements of an aggregate object (such as a list or collection) sequentially without exposing its underlying representation.
Table of Content
- What is the Iterator Design Pattern?
- Components of Iterator Design Pattern
- Iterator Design Pattern example
- When to use Iterator Design Pattern
- When to not use Iterator Design Pattern