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.
Reference: Java design mode iterator
1. First define a container collection interface.
Package com. njupt. ZHB. Learn. iterator; public interface collection {void add (Object O); int size (); iterator ();}
2. Define an iterator Interface
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.
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 () {return New arraylistiterator ();} private class arraylistiterator implements iterator {private int currentindex = 0; @ overridepublic Boolean hasnext () {If (currentindex> = index) return false; else return true ;}@ overridepublic object next () {object o = objects [currentindex]; currentindex ++; return o ;}}}
4. Write a testProgramTestmain
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:
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 is used everywhere in the object-orientedPolymorphism.Function in the subclass of an API call.Source codeDownload:
Http://download.csdn.net/detail/nuptboyzhb/5755295