Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/45599951
I. Overview
Given a language, define a representation of its grammar and define an interpreter that interprets the sentences in the language using that representation.
Second, applicability
1. Access the contents of an aggregated object without exposing its internal representation.
2. Support for multiple traversal of aggregation objects.
3. Provide a unified interface for traversing different aggregation structures (that is, support for polymorphic iterations).
Third, participants
The 1.Iterator iterator defines an interface for accessing and traversing elements.
The 2.ConcreteIterator concrete iterator implements the iterator interface. Tracks the current position on the aggregation pass-through duration.
The 3.Aggregate aggregation defines the interface that creates the corresponding iterator object. The 4.ConcreteAggregate concrete aggregation implements an interface that creates an appropriate iterator that returns an appropriate instance of Concreteiterator.
Four, class diagram
V. Examples
Iterator
Package com.lyz.design.iterator;/** * Iterator * @author Liuyazhuang * */public interface iterator { Object next ( ); void first (); void last (); Boolean Hasnext ();}
Concreteiterator
Package com.lyz.design.iterator;/** * Concreteiterator * @author Liuyazhuang * */public class Iteratorimpl Implements Iterator { private list list; private int index; Public Iteratorimpl (List list) { index = 0; this.list = list; } public void First () { index = 0; } public void Last () { index = list.getsize (); } Public Object Next () { Object obj = List.get (index); index++; return obj; } public Boolean Hasnext () { return index < List.getsize ();} }
Aggregate
Package com.lyz.design.iterator;/** * Aggregate * @author Liuyazhuang * */public interface List { iterator Iterat or (); Object get (int index); int GetSize (); void Add (Object obj);}
concreteaggregate
Package com.lyz.design.iterator;/** * Concreteaggregate * @author Liuyazhuang * */public class Listimpl implements Li St { private object[] list; private int index; private int size; Public Listimpl () { index = 0; size = 0; List = new object[100]; } Public Iterator Iterator () { return to new Iteratorimpl (this); } Public Object get (int index) { return list[index]; } public int GetSize () { return this.size; } public void Add (Object obj) { list[index++] = obj; size++;} }
Test
Package com.lyz.design.iterator;/** * Test * @author Liuyazhuang * */public class Test {public static void main (Strin G[] args) { list list = new Listimpl (); List.add ("a"); List.add ("B"); List.add ("C"); The first iteration of Iterator it = List.iterator (); while (It.hasnext ()) { System.out.println (It.next ()); } System.out.println ("====="); The second iteration means for (int i = 0; i < list.getsize (); i++) { System.out.println (List.get (i));} } }
result
Abc=====abc
On the Java design pattern--iterator mode (interator)