Iterator Pattern
Iterator Pattern
Iterator pattern is very commonly used design pattern in Java and .Net programming environment. This pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation.
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.
Let’s understand this through an example. Suppose we are creating a notification bar in our application that displays all the notifications which are held in a notification collection. NotificationCollection provides an iterator to iterate over its elements without exposing how it has implemented the collection (array in this case) to the Client (NotificationBar).
The class diagram would be:

Below is the Java implementation of the same:
Output:
-------NOTIFICATION BAR------------ Notification 1 Notification 2 Notification 3
Notice that if we would have used ArrayList instead of Array there will not be any change in the client (notification bar) code due to the decoupling achieved by the use of iterator interface.
Comments
Post a Comment