Iterator Pattern

Prakash Sharma
2 min readNov 4, 2022

--

This is the 3rd blog in the series of must-know design patterns. In this blog, we will be understanding the iterator pattern.

My previous design pattern blogs —

Problem statement — we are given a ProductCollection class that has a list of products. we have to traverse the list and print its content.

In the basic approach, we will create a class called Products and expose the list of products. let’s check the code

Then we can simply use it as follow

This will output the product's name to the console.

Now, what is the problem with this implementation?
If we look at the API that is exposing the products

public List<Product> getProducts(){
return this.products;
}

and we are using it as follows in client end

List<Product> storedProducts = products.getProducts();
  • If tomorrow for some reason you have to change the internal implementation from List<Product> to LinkedList<Product> in that case, your client-side code will be broken.
  • Also, we should not expose the internal details.

How do we fix it? 🤨

An iterator pattern is used to traverse the collection of objects without exposing the internal details of the storage.

We will create an iterator interface that has some basic methods to traverse any collection.

Create concrete implementation as an inner class inside the product collection so that it has access to the required details.

ProductCollection class is providing a well-defined API for iterating the collection. It’s an implementation of our collection interface which provides an abstraction of the type of collection. The collection interface is not part of our iterator pattern so you can avoid it and write a simple method like below.

@Override
public ProductIterator getIterator() {
return new ProductIterator(this);
}

Our product class is simple like a record.

Result section

This will output the name —

Product{id=1, name='Television'}
Product{id=2, name='Keyboard'}
Product{id=3, name='Laptop'}
Product{id=4, name='Mobile'}

So, we have implemented the iterator pattern, if you see we are not exposing any internal details to client so tomorrow if we change the internal implementation of product storage there won’t be any affect on the client side code.

My previous design pattern blogs —

--

--