Illustration: Java 23 design patterns Note 1, Java 23 Design Patterns
Iterator pattern 1.1 Iterator Pattern
The element code in the array arr is displayed in Java as follows:
1 for (int I = 0; I <arr. length; I ++) 2 {3 bytes M. out. println (arr [I]); 4}
Many elements are saved in the array. By specifying the array subscript, we can select any element from it.
In the for statement, I ++ is used to increase the I value by 1 after each loop, so that the next element, the next element, and the next element in the array can be accessed, implements the function of traversing array elements one by one from start to end.
Abstract and generalize the role of the cyclic variable I here to form a pattern that becomes the lterator pattern in the design pattern.
The Iterator mode is used to traverse the set in sequence in the dataset, referred to as the "Iterator" mode.
1.2 sample program
Purpose: place the book in the bookshelf and display the name of the book in sequence.
Aggregate Interface
The Aggregate interface is the interface of the set to be traversed. The class implementing this interface will become a set that can save multiple elements, just like an array. Aggregate indicates clustering.
------------------------------------------------------------
Description
Aggregate indicates the set Interface
Iterator interfaces for traversing a set
Book indicates the Book class
BookShelf indicates the class of the BookShelf
BookShelfIterator traverses the class of the bookshelf
Main test program behavior class
-------------------------------------------------------------