Javatpoint Logo
Javatpoint Logo

Iterator Pattern

According to GoF, Iterator Pattern is used "to access the elements of an aggregate object sequentially without exposing its underlying implementation".

The Iterator pattern is also known as Cursor.

In collection framework, we are now using Iterator that is preferred over Enumeration.

java.util.Iterator interface uses Iterator Design Pattern.

Advantage of Iterator Pattern

  • It supports variations in the traversal of a collection.
  • It simplifies the interface to the collection.

Usage of Iterator Pattern:

It is used:

  • When you want to access a collection of objects without exposing its internal representation.
  • When there are multiple traversals of objects need to be supported in the collection.

Example of Iterator Pattern

Let's understand the example of iterator pattern pattern by the above UML diagram.

UML for Iterator Pattern:

Iterator Pattern UML

Implementation of above UML

Step 1

Create a Iterartor interface.

Step 2

Create a Container interface.

Step 3

Create a CollectionofNames class that will implement Container interface.

File: CollectionofNames.java

Step 4

Create a IteratorPatternDemo class.

File: IteratorPatternDemo.java

Output





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials