The so-called Iterator mode provides a unified access mode for different containers. This article uses java containers as an example to simulate the principle of Iterator. For more information, see
1. First define a container Collection interface.
Copy codeThe Code is as follows:
Package com. njupt. zhb. learn. iterator;
Public interface Collection {
Void add (Object o );
Int size ();
Iterator iterator ();
}
2. Define an Iterator Interface
Copy codeThe Code is as follows:
Package com. njupt. zhb. learn. iterator;
Public interface Iterator {
Object next ();
Boolean hasNext ();
}
3. Define an ArrayList to implement the Collection interface, and write an internal class that implements the Iterator interface.
Copy codeThe Code is as follows:
Package com. njupt. zhb. learn. iterator;
Import com. njupt. zhb. learn. iterator. Collection;
Public class ArrayList implements Collection {
Object [] objects = new Object [10];
Int index = 0;
Public void add (Object o ){
If (index = objects. length ){
Object [] newObjects = new Object [objects. length * 2];
System. arraycopy (objects, 0, newObjects, 0, objects. length );
Objects = newObjects;
}
Objects [index] = o;
Index ++;
}
Public int size (){
Return index;
}
Public Iterator iterator (){
Return new ArrayListIterator ();
}
Private class ArrayListIterator implements Iterator {
Private int currentIndex = 0;
@ Override
Public boolean hasNext (){
If (currentIndex> = index) return false;
Else return true;
}
@ Override
Public Object next (){
Object o = objects [currentIndex];
CurrentIndex ++;
Return o;
}
}
}
4. Compile the test program TestMain.
Copy codeThe Code is as follows:
Package com. njupt. zhb. learn. iterator;
Import com. njupt. zhb. learn. iterator. ArrayList;
Public class TestMain {
Public static void main (String [] args ){
Collection c = new ArrayList ();
For (int I = 0; I <15; I ++ ){
C. add ("string" + I );
}
System. out. println (c. size ());
Iterator it = c. iterator ();
While (it. hasNext ()){
Object o = it. next ();
System. out. println (o. toString () + "");
}
}
}
Running result:
Copy codeThe Code is as follows:
15
String 0
String 1
String 2
String 3
String 4
String 5
String 6
String 7
String 8
String 9
String 10
String 11
String 12
String 13
String 14
From the above, we can see that the design pattern uses object-oriented polymorphism everywhere. The API calls the function in the subclass.Click to download source code