Iterator Pattern is a very common design pattern in Java and .Net programming environments. This pattern is used to sequentially access the elements of the collection object without knowing the underlying representation of the collection object.
The iterator mode is a behavioral mode.
Intent: Provides a way to sequentially access individual elements of an aggregated object without exposing the internal representation of the object.
Main solution: Different ways to traverse the entire integration object.
When to use: Traverse an aggregate object.
How to solve: Hand over the responsibility of moving between elements to the iterator instead of the aggregate object.
Key Code: Define the interface: hasNext, next.
Application example: iterator in JAVA.
Advantages: 1. It supports traversing an aggregate object in different ways. 2. The iterator simplifies the aggregation class. 3. There can be multiple traversals on the same aggregate. 4. In the iterator mode, it is convenient to add new aggregation classes and iterator classes without modifying the original code.
Disadvantages: Since the iterator pattern separates the responsibility of storing data from traversing data, adding a new aggregate class requires adding a new iterator class, and the number of classes is increased in pairs. To some extent, the complexity of the system has increased.
Usage scenarios: 1. Access the contents of an aggregated object without exposing its internal representation. 2, need to provide a variety of traversal methods for the aggregate object. 3. Provide a unified interface for traversing different aggregation structures.
Note: The iterator pattern separates the traversal behavior of the collection object, abstracting an iterator class to handle, so that you can not expose the internal structure of the collection, but also allow the external The code transparently accesses the data inside the collection.
We will create an Iterator interface that describes the navigation method and a Container interface that returns the iterator. Entity classes that implement the Container interface will be responsible for implementing the Iterator interface.
IteratorPatternDemo, our demo class uses the entity class NamesRepository to print the Names stored as a collection in NamesRepository .
Create an interface:
Create an entity class that implements the Container interface. This class has an inner class NameIterator that implements the Iterator interface.
Use NameRepository to get the iterator and print the name.
Executing the program, outputting results:
Name : Robert Name : John Name : Julie Name : Lora