When it comes to iterators, we can't help but think of iterator patterns, so I'll start with an iterator pattern.
There are often some data structures in our applications:
They are a collection of data that, if you know their internal implementation structure, can access them, their respective internal storage structure is different, various sets have their own applications. Speaking of which, you may come up with a whole bunch of such collections: List,hashtable,arraylist and so on. These collections each have their own personalities, and that is the reason for their existence. But if you want to traverse it you have to know its internal storage details, as a collection element, the internal details of the exposure is certainly not good, so the client program is not stable, when you change the collection object, such as the list can not meet the needs of the time, you change to Hashtable, because to Before the client program too much attention to the list inside the details of implementation, so not very good transplant. And the iterator pattern is meant to solve this problem:
Provides a consistent way to access elements in a collection object without exposing the internal representation of the collection object.
For example, there is a need to iterate through the elements in a collection and then output, but it does not define what kind of collection the collection is, that is, the future set may change.
Thinking:
The collection will change, this is the change point, the set changes, the traversal method also changes, we want to ensure that the method of traversal is stable, then we need to block out the details. We find the point of change, we isolate it (generally using interface as an isolation): Suppose all the sets inherit from the ICollection interface, which is used to isolate the specific set, shielding the collection behind the interface, As a traversal we certainly need such a number of methods: MoveNext, current, since ICollection is responsible for data storage, the responsibility of a single, then a new interface called iterator bar, each specific set has its own corresponding iterator implementation: