Iterator Pattern Design Patterns in Java

The iterator pattern comes under the behavioral patterns. The design uses iterator object, which stores the track of the current object in the list and the next object which is supposed to be iterated next. Iterator pattern takes the responsibility for the accessing and passing of the objects through the list and storing them in an iterator object.

Iterator Pattern

According to the Gang of Four:

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Iterator, in the sense of computer programming, is an object that allows the programmer to traverse a container, specifically lists. The interface of the container is the source for different types of iterators. Iterators are often tightly linked to the container to allow the operational semantics of the iterator.

To design, versatile and reusable object-oriented software, there are 23 well-known design patterns, the iterator pattern is one of them. The idea of Iterator pattern is to give a way to access the elements of the comprehensive object in a sequential manner without having the need to know about its hidden representation. For example, if a person writes a simple binary search algorithm in Java language. Due to the strong language used, the function signature is most likely to couple the algorithm to the particular collection types. To decouple the collection types from the algorithm, the iterator interface is required. This allows the algorithm to cover various types of data structures. This way, the user does not need to write separate algorithms for each data type and can make the algorithm functions for more than one data type, just by recycling it.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Patterns“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.
Spring-5-Design-Pattern

Benefits of using the Iterator pattern

There are following benefits of the Iterator pattern:

  • Easily access the items of the collection.
  • You can use multiple to access the item from the collection, because it support lot of variations in the traversal.
  • It provides a uniform interface for traversing different structures in a collection.

The iterator pattern is used in the object-oriented programming. It is the kind of design pattern where an iterator is used to traverse through a container and its elements, this helps in decoupling the algorithm and the elements of the container. Though, in some cases, it is not possible to decouple the algorithms because they are specified by the container (depends directly on it). The pattern prevents from the representation (data structures) of the container, to be exposed. The procedure can easily be performed with the representation, hidden. For each new data type, there will be no need for new algorithms to be defined. Defining and writing down new algorithms for each different data type can consume time and energy both. The iterator pattern helps save time and energy.

Characterizing entry and traversal operations in the comprehensive interface may be unbendable in order that it commits the collection to specific access and traversal operations. This makes it almost impossible to add new operations in future, not unless the collection interface has been changed in respective order.

The iterator pattern helps to define a separate object, iterator, that takes responsibility to access and traverse the collection object. This way, other objects do not get jumbled up. The clients that use an iterator, in order to access or traverse the container or elements of the container, will not know about its underlying data structure or representation. Various types of iterators can be used to access and traverse in different ways. By declaring new iterators, new traversal operations can be defined.

UML Class Structure

Let’s see the following UML diagram is showing the all components of Iterator design pattern:

Iterator Pattern UML diagram

Iterator
It is an interface or abstarct class for accessing and traversing items of the collections.
ConcreteIterator
It is implementation of the Iterator interface.
Aggregate
It is an interface to create an Iterator object
ConcreteAggregate
It is implementation of the Aggregate interface, it implements the Iterator creation interface to return an instance of the proper ConcreteIterator.

Example of Iterator Design Pattern

java.util.Iterator interface uses Iterator Design Pattern.

Step 1: Create interfaces.

Iterator.java

public interface Iterator {
   public boolean hasNext();
   public Object next();
}

Step 2: Container.java

public interface Container {
   public Iterator getIterator();
}

Step 3: Create concrete class implementing the Container interface.

This class has an inner class NameCollectionIterator implementing the Iterator interface.

NameCollection.java

public class NameRepository implements Container {
   public String names[] = {"Dinesh", "Anamika","Arnav", "Adesh", "Vinesh"};

   @Override
   public Iterator getIterator() {
      return new NameCollectionIterator();
   }

   private class NameCollectionIterator implements Iterator {

      int index;

      @Override
      public boolean hasNext() {
      
         if(index < names.length){
            return true;
         }
         return false;
      }

      @Override
      public Object next() {
      
         if(this.hasNext()){
            return names[index++];
         }
         return null;
      }		
   }
}

Step 4: Create a IteratorPatternDemo class.

IteratorPatternDemo.java

public class IteratorPatternDemo {
	
   public static void main(String[] args) {
      NameRepository namesRepository = new NameRepository();

      for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
         String name = (String)iter.next();
         System.out.println("Name : " + name);
      } 	
   }
}

Step 4: Let’s run this demo class and verify the output.

Name : Dinesh
Name : Anamika
Name : Arnav
Name : Adesh
Name : Vinesh
Previous
Next