This is the 22nd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
An overview of the
The Iterator Pattern is an object behavior Pattern that provides a way to iterate over the elements of a container object without exposing the inner details of the object.
structure
-
Aggregate (Abstract aggregation class) : Used to store and manage element objects, usually abstract classes or interfaces.
-
ConcreteAggregate: Implements a method for creating iterators.
-
Iterator: Defines an interface that accesses and iterates over elements, typically an abstract class or interface.
-
ConcreteIterator: this implements an abstract iterator interface that iterates through aggregate objects, marking the current location in the aggregate object with a cursor in the ConcreteIterator.
advantages
- It provides a unified method to traverse the aggregate object. When the client traverses the collection, it only needs to get the iterator without knowing the specific composition of the aggregate, which conforms to Demeter’s law.
- Iterators are interface oriented and can iterate over aggregate objects in different ways. The customer does not need to consider the type of aggregate, conforming to the open closed principle.
- The management of objects is separated from traversal. Set changes only affect aggregate objects, traversal changes only affect iterators, in line with the single responsibility principle.
disadvantages
- Each aggregate object requires one iterator, which can result in too many iterators that are difficult to manage and maintain.
- Since the iterator pattern separates the responsibility of storing data and traversing data, adding new aggregation classes needs to correspond to adding new iterator classes, and the number of classes increases in pairs, which increases the complexity of the system to some extent.
- Abstract iterators are difficult to design and need to fully consider the future expansion of the system, which is not conducive to expansion.
Application scenarios
- You need to provide multiple traversals for an aggregate object.
- You need a unified interface for traversing different aggregation structures.
- You need to access the contents of an aggregate object without exposing its internals.
Applications in the JDK
Both java.util.Iterator and java.util.Enumeration use the Iterator pattern in the JDK.