1. Iterator mode (Iteratormode)
Definition: The iterator pattern is the sequential access to the objects in the aggregation, in general, the set is not often.
There are two objects: one is a clustered object : The object that needs to be traversed. The second is an iterator object : Used to iterate over a clustered object
Diagram:
2. Example
2.1 Integrated
Collection interface: Get, length method public interface Collection { //collection length int size ();//Get element char get (int pos);//add element void put (char c);// Gets the iterator iterator iterator ();} Set subclass class MyCollection implements collection{ //Storage elements Collection StringBuilder sb=new StringBuilder ();// Gets the length @overridepublic int size () {//TODO auto-generated method Stubreturn sb.length ();} Gets the element @overridepublic char get (int pos) {//TODO auto-generated method Stub if (pos>=0&&pos<= Sb.length ()-1) return Sb.charat (POS); return (Character) null;} Create your own Iterator and return @overridepublic Iterator Iterator () {//TODO auto-generated method Stubreturn new Myiterator (this);} //add element @overridepublic void put (char c) {//TODO auto-generated Method Stubsb.append (c);}}
2.2 iterators
The iterator interface public interface Iterator { boolean hasnext ();//Determines if there is a char next ();//The previous character char previous ();//After a character char First ();//returns the initial character}class Myiterator implements Iterator{collection c=null;//pointer: subscript int pos=-1;public Myiterator pointing to an element ( Collection c) {this.c=c;} @Overridepublic Boolean Hasnext () {//pointer moves down and determines if the pointer exists pos++;if (pos<c.size ()) return True;return false;} @Overridepublic Char Next () {//TODO auto-generated method Stubreturn C.get (POS);} @Overridepublic Char Previous () {//TODO auto-generated method Stubreturn C.get (pos-1);} @Overridepublic Char First () {//TODO auto-generated method Stubreturn c.get (0);}}
2.3 Testing
public class Test {public static void main (string[] args) {//TODO auto-generated method stub Collection mycol=new MyC Ollection (); Mycol.put (' a '); Mycol.put (' B '); Mycol.put (' C '); Iterator it=mycol.iterator (); System.out.print ("Print set:"); while (It.hasnext ()) { char c=it.next (); System.out.print (c);}}
2.4 Running Results
Print Collection: ABC
java-design mode (behavioral)-"iterator mode"