/*
*迭代器(Iterator)模式:提供货一种方法顺序反问一个聚合对象中的各个元素。
*/
ConcreteAggregate a = new ConcreteAggregate(); a[0] = "A"; a[1] = "B"; a[2] = "C"; a[3] = "D"; Iterator i = new ConcreteIterator(a); object item = i.First(); while (!i.IsDone()) { Console.WriteLine("{0} 请买车票! ", i.CurrentItem()); i.Next(); } Console.ReadLine(); /// <summary> /// 迭代器(Iterator) 抽象类 /// </summary> abstract class Iterator { public abstract object First(); public abstract object Next(); public abstract bool IsDone(); public abstract object CurrentItem(); } /// <summary> /// Aggregate 集聚抽象类 /// </summary> abstract class Aggregate { public abstract Iterator CreateIterator(); } /// <summary> /// ConcreteIterator 具体迭代器 /// </summary> class ConcreteIterator : Iterator { //创建一个具体集聚类对象 private ConcreteAggregate aggregate; private int current = 0; //初始化具体集聚类传入对象 public ConcreteIterator(ConcreteAggregate aggregate) { this.aggregate = aggregate; } public override object First() { return aggregate[0]; } public override object Next() { object ret = null; current++; if (current < aggregate.Count) ret = aggregate[current]; return ret; } public override bool IsDone() { return current >= aggregate.Count ? true : false; } public override object CurrentItem() { return aggregate[current]; } } /// <summary> /// 具体 集聚类 /// </summary> class ConcreteAggregate : Aggregate { private IList<object> items = new List<object>(); public override Iterator CreateIterator() { 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); } } }
在.net中IEumerator 已经为你准备好了接口,你只要去实现它就好。
其实就一个 foreach 循环的底层方法。 封装后就是foreach 遍历集合
public interface IEumerator { object Current { get; } bool MoveNext(); void Reset(); } public interface IEnumerable { IEumerator GetEnumerator(); }