Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/39807741
Iterator mode (Iterator): Provides a way to sequentially access individual elements in an aggregated object without exposing their internal representations.
First, UML modeling:
Second, the Code implementation
/** * Example: iterator mode * */interface Iterator {/** forward */public object Previous ();/** */public object Next ()/** determine if there is a next element */p Ublic boolean Hasnext ();} Interface Collection {public Iterator Iterator ();/** gets an element from the collection */public Object get (int i);/** gets the collection size */public int size (); }/** * Set */class mycollection implements Collection {private string[] Strarray = {"AA", "BB", "CC", "DD"}; @Overridepubl IC Iterator Iterator () {return new myiterator (this);} @Overridepublic Object Get (int i) {return strarray[i];} @Overridepublic int size () {return strarray.length;}} /** * Iterator */class Myiterator implements Iterator {private Collection collection;private int pos = -1;public Myiterator (Col Lection collection) {this.collection = collection;} @Overridepublic Object Previous () {if (pos > 0) {pos--;} Return Collection.get (POS);} @Overridepublic Object Next () {if (pos < Collection.size ()-1) {pos++;} Return Collection.get (POS);} @Overridepublic Boolean hasnext () {if (pos < Collection.size ()-1) {return true;}return false;}} /** * Client Test class * * @author Leo */public class Test {public static void main (string[] args) {/** * Instantiate container */collection Collec tion = new mycollection ();/** * Create iterator */iterator Iterator = Collection.iterator ();/** * Iterates through the elements in the collection */while (iterator.hasnext ()) {System.out.println (Iterator.next ());}}}
Third, the application scenario
Traverse, access an element in the collection, and so on
Iv. Summary
The iterator pattern is the sequential access to the objects in the collection, which contains two meanings: the object that needs to be traversed, the collection object, and the iterator object, which is used to iterate through the collection object .
Java Design Patterns Rookie series (11) Modeling and implementation of iterator mode