The iterator design pattern is widely used for traversing in a set.
Internal classes are used here.
The following is a simplified design pattern for an iterator:
1. iterator Interface
Public interface iterator <e >{ Boolean hasnext (); e next ();}
2. Internal class
Public class Outer {private object [] item; private int size = 0; Public outer (int n) {If (n <= 0) {system. out. println ("out of bounds");} item = new object [N];} public void add (Object object) {item [size ++] = object ;} public iterator <Object> iterator () {return New ITER ();} public class ITER implements iterator <Object> {int current = 0; @ overridepublic Boolean hasnext () {Return Current <size ;}@ overridepublic object next () {If (current >= size) {return NULL;} return item [current ++] ;}}
3. Test
Public static void main (string [] ARGs) {outer = new outer (10); outer. add (new object (); outer. add (new object (); outer. add (new object (); outer. add (new object (); outer. add (new object (); iterator <Object> iterator = outer. iterator (); While (iterator. hasnext () {system. out. println (iterator. next (). tostring ());}}
Output result
[Email protected] [email protected] [email protected] [email protected] [email protected]
It is a simple but very usable design model, but the premise is to understand the internal class
Design Pattern iterator