Sequential access to objects in the aggregation, primarily for collections. One is the object that needs to be traversed, that is, the aggregation object, and the second is the iterator object, which is used to iterate over the clustered object. Iterative sub-patterns provide a uniform interface method for iterating through the collection. So that the client does not need to know the aggregation of the internal structure can be able to traverse the aggregation and so on. The iterator pattern is the standard access method used to traverse the collection class. It abstracts the access logic from different types of collection classes, thus avoiding exposing the internal structure of the collection to the client.
For example, if you are not using iterator, the way to traverse an array is to use an index:
for (int i=0; i<array.size (); i++) {
.... get (i) ...}
Access to a linked list (LinkedList) must also use the while loop:
while ((E=e.next ())!=null) {... e.data () ...}
Both methods the client must know in advance the internal structure of the collection, the Access code and the collection itself is tightly coupled, unable to separate the access logic from the collection class and client code, each collection corresponding to a traversal method, the client code can not be reused.
Even more frightening, if you later need to change ArrayList to LinkedList, the original client code must all be rewritten.
To solve these problems, the iterator pattern always uses the same logic to iterate through the collection:
for (Iterator it = C.iterater ();
It.hasnext (); ) { ... }
The secret is that the client itself does not maintain a "pointer" that iterates through the collection, and that all internal states (such as the current element's position and whether there is a next element) are maintained by iterator, and this iterator is generated by a factory method of the collection class, so it knows how to traverse the entire collection.
The client never deals directly with the collection class, it always controls the iterator, sends a "forward", "backward", "Fetch current" command to it, and can traverse the entire collection indirectly.
Well, there are 5 main objects in the iterative sub-pattern
Java Design pattern----iterative sub-pattern