Iterator pattern in one of the behavioral pattern and it’s used to provide a standard way to traverse through a group of Objects. Iterator pattern is widely used in java collection framework where Iterator interface provides methods for traversing through a collection.
The logic for iteration is embedded in the collection itself and it helps client program to iterate over them easily. Iterator pattern is not only about traversing through a collection; we can provide different kind of iterators based on our requirements.
Iterator pattern hides the actual implementation of traversal through the collection and client programs just use iterator methods. An Iterator object contains public methods to allow a client object to navigate through the list of objects within the container.
- Defines an interface for accessing and traversing elements.
- Implements the Iterator interface.
- Keeps track of the current position in the traversal of the aggregate.
- Defines an interface for creating an Iterator object.
- Implements the Iterator creation interface to return an instance of the proper ConcreteIterator.
When to use the Iterator Design Pattern:
Use the Iterator pattern:
- To access an aggregate object’s contents without exposing its internal representation.
- To support multiple traversals of aggregate objects.
- To provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).
- Iterator pattern is useful when you want to provide a standard way to iterate over a collection and hide the implementation logic from client program.
Iterator Pattern in JDK: