Definition of the iterator pattern

Definition: Provides a way to access elements of a container object without exposing the inner details of the object

Its class diagram is as follows:

 

Roles:

  1. Iterator: An abstract Iterator is responsible for defining the interface through which elements are accessed and iterated, and there are basically three fixed methods: first() to get the first element, next() to get the next element, and isDone() to see if the end is reached
  2. ConcreteIteraor: Implements an abstract iterator that iterates through container elements
  3. Aggregate Abstract container: Responsible for providing the interface to create concrete iterators
  4. ConcreteAggregate: Method of implementing abstract container definitions, creating objects that hold iterators

Its code implementation is as follows:

Abstract iterators:

 

Concrete iterators:

 

Abstract container:

 

Specific container:

 

Scenario:

 

Application of the iterator pattern

In fact, almost all high-level languages now implement iterators, and very few projects write iterators independently anymore.

Iterators are now used more and more widely, even as a basic tool


If you’re doing Java development, try not to write your own iterator patterns. Using an Iterator provided by Java will generally suffice