This pattern allows you to access elements from a collection in a sequential order without disclosing the underlying structure. It has read-only access and no access to the internal collection.
Examples of Iterator Patterns
Examples of iterator patterns include:
Collection Iteration
Collection Elements Ordering (Asc, Desc)
Iterator pattern with UML Diagram
The classes, interfaces, & objects in the above UML class diagram are defined as follows.
Client: This class includes an object collection and uses the iterator's Next action to retrieve objects from the aggregate in the appropriate order.
Iterator: This interface defines operations for accessing collection elements in a sequential order.
ConcreteIterator: This class implements the Iterator interface.
Aggregate: This interface describes the operation for creating an iterator.
ConcreteAggregate: This class implements the Aggregate interface.
When Should You Use the Iterator Design Pattern?
The iterator design pattern is useful for the following cases:
Allows sequential access to the elements of a collection object without understanding the underlying structure.
Multiple or concurrent iterations are necessary for collection elements.
Offers a standardized interface for accessing the collection elements.
Advantages of the Iterator Design Pattern
Separation of Concerns: separates the iteration algorithms from the collection classes themselves.
Multiple Traversals: Enables various ways to traverse a collection at the same time.
Uniform Interface: Provides a consistent interface for accessing various data structures.
Encapsulation: Captures the internal structure of a collection's navigation and access.