The iterator provides a way to access an aggregate object sequentially without exposing the internal details of the object. Net foreach is a typical iterator mode.
Figure:
Code: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + logs/nytvstwvcd4kpha + PHByZSBjbGFzcz0 = "brush: java;"> class Program {static void Main (string [] args) {ConcreteAggregate a = new ConcreteAggregate (); a [0] = "laruence"; a [1] = "xiao"; a [2] = "Luggage"; a [3] = "foreigner "; a [4] = "internal employee"; a [5] = "thief"; Iterator I = new ConcreteIterator (a); object item = I. first (); while (! I. IsDone () {Console. WriteLine ("{0} Please buy a ticket! ", I. currentItem (); I. next ();} Console. read () ;}// the abstract Iterator class abstract class Iterator {public abstract object First (); public abstract object Next (); public abstract bool IsDone (); public abstract object CurrentItem () ;}// Aggregate abstract class Aggregate {public abstract Iterator createIterator (); // create Iterator} // class ConcreteIterator of the specific Iterator class: iterator {private ConcreteAggregate aggregate; private in T current = 0; public ConcreteIterator (ConcreteAggregate aggregate) {this. aggregate = aggregate;} public override object First () {// throw new NotImplementedException (); return aggregate [0];} public override object Next () {// throw new NotImplementedException (); object ret = null; current ++; if (current <aggregate. count) {ret = aggregate [current];} return ret;} public override bool IsDone () {// Throw new NotImplementedException (); return current> = aggregate. Count? True: false;} public override object CurrentItem () {// throw new NotImplementedException (); return aggregate [current];} class ConcreteAggregate: aggregate {// declare an IList generic variable to store the Aggregate object private IList <object> items = new List <object> (); public override Iterator createIterator () {// throw new NotImplementedException (); return new ConcreteIterator (this);} public int Count {get {return items. count ;}} public object this [int index] {get {return items [index];} set {items. insert (index, value );}}}
Running result: