usingSystem;namespaceconsoleapplication9{classProgram {/// <summary> ///The iterator pattern provides a way to sequentially access individual elements in an aggregate object (understood as a collection object) .///Without exposing the object's internal representation, so that it does not expose the internal structure of the collection,///It also allows external code to transparently access the data inside the collection. /// </summary> /// <param name= "args" ></param> Static voidMain (string[] args) {Iterator Iterator; Ilistcollection List=Newconcretelist (); Iterator=list. Getiterator (); while(iterator. MoveNext ()) {inti = (int) iterator. GetCurrent (); Console.WriteLine (i.ToString ()); Iterator. Next (); } console.read (); } //Abstract Aggregation Classes Public Interfaceilistcollection {Iterator getiterator (); } //iterator abstract class Public InterfaceIterator {//whether the next object exists BOOLMoveNext (); //get Subscript ObjectObject GetCurrent (); //Subscript plus 1 voidNext (); //under SD 0 voidReset (); } //Specific aggregation classes Public classconcretelist:ilistcollection {int[] collection; PublicConcretelist () {collection=New int[] {2,4,6,8 }; } PublicIterator Getiterator () {return NewConcreteiterator ( This); } Public intLength {Get{returncollection. Length; } } Public intGetElement (intindex) { returnCollection[index]; } } //Specific iterator Classes Public classConcreteiterator:iterator {//iterators need to refer to a collection object for traversal operations. Privateconcretelist _list; Private int_index; Publicconcreteiterator (concretelist list) {_list=list; _index=0; } Public BOOLMoveNext () {if(_index <_list. Length) {return true; } return false; } PublicObject GetCurrent () {return_list. GetElement (_index); } Public voidReset () {_index=0; } Public voidNext () {if(_index <_list. Length) {_index++; } } } }}
16. Iterator mode (Iterator pattern)