抽离集合对象的遍历职责。
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { public interface IListCollection { Iterator GetIterator(); } public interface Iterator { bool MoveNext(); object GetCurrent(); void Next(); void Reset(); } public class ConcreteList:IListCollection { private int[] collection; public ConcreteList() { collection = new int[] {2, 4, 6, 8}; } public Iterator GetIterator() { return new ConcreteIterator(this); } public int Length { get { return collection.Length; } } public int GetElement(int index) { return collection[index]; } } public class ConcreteIterator:Iterator { private ConcreteList cList; private int index; public ConcreteIterator(ConcreteList clist) { this.cList = clist; index = 0; } public bool MoveNext() { if (index < cList.Length) { return true; } return false; } public object GetCurrent() { return cList.GetElement(index); } public void Next() { if (index < cList.Length) { index++; } } public void Reset() { index = 0; } } static void Main(string[] args) { Iterator iterator; IListCollection cList = new ConcreteList(); iterator = cList.GetIterator(); while (iterator.MoveNext()) { Console.WriteLine(iterator.GetCurrent().ToString()); iterator.Next(); } } } }