Iterator Design Pattern

Anubhav Gupta

--

The Iterator Pattern in Java is a behavioral design pattern that provides a way to access the elements of a collection (such as a list, set, or array) sequentially without exposing the underlying implementation. This pattern is useful when you need to iterate through a collection in a consistent way while keeping the internal details of the collection hidden.

Components of the Iterator Pattern:

Iterator Interface: Defines methods to traverse the elements.

Concrete Iterator: Implements the iterator interface.

Aggregate Interface: Defines a method that returns an iterator object.

Concrete Aggregate: Implements the aggregate interface and returns an instance of the iterator.

Now if we change the data structure e.g. fix sized array or stack, our code

might not work.

Now, these are the fairly simple and limited classes but in real time we might have used this logic in multiple places. We have to update the code at multiple places, as the underlying data structure change.

This solution violates the SRP i.e. Single Responsibility Principle.

Now, BrowserHistory has two responsibilities.

1. History Management

2. Iterator Management

Now, each class has a single responsibility.

Benefits of the Iterator Pattern:

1. Encapsulation: It hides the underlying structure of the collection.

2. Uniformity: You can traverse different types of collections (arrays, lists, etc.) in the same way using an iterator.

3. Decoupling: It decouples the collection from the iteration logic.

Array Type Iterator

Iterator Interface

Aggregate Interface

Concrete Aggregator and Concrete Iterator

List Type Iterator

Iterator Interface

Aggregate Interface

Concrete Aggregator and Concrete Iterator

Main

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Anubhav Gupta
Anubhav Gupta

Written by Anubhav Gupta

Machine Learning , Computer Vision and Deep Learning Enthusiast

Responses (1)

Write a response