/*
*Iterator Pattern:主题就是使用迭代器,遍历集合中的每一项
*/using System;using System.Collections.Generic;using System.Collections;namespace Pattern01
{classProgram{staticvoidMain(string[] args){ConcreteAggregate a =newConcreteAggregate();
a[0]="Item A";
a[1]="Item B";
a[2]="Item C";
a[3]="Item D";//添加其他数据类型
a[4]=16;
a[5]=false;// 创建一个迭代器Iterator i = a.CreateIterator();
Console.WriteLine("Iterating over collection:");object item = i.First();while(item !=null){
Console.WriteLine(item);
item = i.Next();//}
Console.ReadKey();}}/// <summary>/// Aggregate--抽象集合/// defines an interface for creating an Iterator object/// </summary>abstractclassAggregate{publicabstractIteratorCreateIterator();}/// <summary>/// ConcreteAggregate--具体集合。/// implements the Iterator creation interface to return an instance of the proper ConcreteIterator/// </summary>classConcreteAggregate:Aggregate{privateArrayList _items =newArrayList();//声明一个集合,用于保存数据项publicoverrideIteratorCreateIterator(){returnnewConcreteIterator(this);//获取迭代器,并将集合与迭代器绑定}publicint Count
{get{return _items.Count;}}publicobjectthis[int index]{get{return _items[index];}set{ _items.Insert(index,value);}}}/// <summary>/// Iterator --抽象迭代器/// defines an interface for accessing and traversing elements./// </summary>abstractclassIterator{publicabstractobjectFirst();publicabstractobjectNext();publicabstractboolIsDone();publicabstractobjectCurrentItem();}/// <summary>/// ConcreteIterator---具体迭代器,实现访问集合中的数据项/// implements the Iterator interface./// keeps track of the current position in the traversal of the aggregate./// </summary>classConcreteIterator:Iterator{privateConcreteAggregate _aggregate;//集合privateint _current =0;publicConcreteIterator(ConcreteAggregate aggregate){this._aggregate = aggregate;//将集合与迭代器中字段绑定,用于遍历集合中的数据项}publicoverrideobjectFirst(){return _aggregate[0];//获取集合中的第一个元素}publicoverrideobjectNext(){object ret =null;if(_current < _aggregate.Count -1){
ret = _aggregate[++_current];}return ret;}publicoverrideobjectCurrentItem(){return _aggregate[_current];}publicoverrideboolIsDone(){return _current >= _aggregate.Count;}}}