Definition: Provides a way to sequentially access individual elements in an aggregated object without exposing their internal representations.
UML Class Diagrams:
1 InterfaceIterator {2 PublicObject Next ();3 Public BooleanHasnext ();4 }5 classConcreteiteratorImplementsiterator{6 PrivateList List =NewArrayList ();7 Private intCursor =0;8 Publicconcreteiterator (List list) {9 This. List =list;Ten } One Public BooleanHasnext () { A if(cursor==list.size ()) { - return false; - } the return true; - } - PublicObject Next () { -Object obj =NULL; + if( This. Hasnext ()) { -obj = This. List.get (cursor++); + } A returnobj; at } - } - InterfaceAggregate { - Public voidAdd (Object obj); - Public voidRemove (Object obj); - PublicIterator Iterator (); in } - classConcreteaggregateImplementsAggregate { to PrivateList List =NewArrayList (); + Public voidAdd (Object obj) { - list.add (obj); the } * $ PublicIterator Iterator () {Panax Notoginseng return Newconcreteiterator (list); - } the + Public voidRemove (Object obj) { A list.remove (obj); the } + } - Public classClient { $ Public Static voidMain (string[] args) { $Aggregate AG =Newconcreteaggregate (); -Ag.add ("Xiao Ming"); -Ag.add ("Little Red"); theAg.add ("Xiao Gang")); -Iterator it =ag.iterator ();Wuyi while(It.hasnext ()) { theString str =(String) It.next (); - System.out.println (str); Wu } - } About}
Design Pattern-iterators