设计模式之迭代器模式

结构

迭代器模式

说明

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。

适用条件

迭代器模式是非常常见的设计模式之一, 适用条件很广, 需要访问聚合对象(数组、集合、列表等)的元素时, 即可使用迭代器模式。

实现

public interface IIterator {

   object CurrentItem();

   void First();

   bool IsDone();

   void Next();

}

public interface IAggregate {

   IIterator CreateIterator();
}

public class ConcreteIterator : IIterator {
   
   private readonly object[] _aggregateItems;
   private int _index;

   public ConcreteIterator(object[] aggregateItems) {
      this._aggregateItems = aggregateItems;
      this._index = 0;
   }

   public object CurrentItem() {
      return this._aggregateItems[this._index];
   }

   public void First() {
      this._index = 0;
   }

   public bool IsDone() {
      return this._index == this._aggregateItems.Length;
   }

   public void Next() {
      this._index += 1;
   }
}


public class ConcreateAggregate : IAggregate {

   private readonly object[] _items;

   public ConcreateAggregate(params object[] items) {
      if (items != null) {
         this._items = new object[items.Length];
         for (var i = 0; i < items.Length; i++) {
            this._items[i] = items[i];
         }
      }
   }
   
   public IIterator CreateIterator() {
      return new ConcreteIterator(this._items);
   }

}

class Client {

   static void Main(string[] args) {
      IAggregate aggregate = new ConcreateAggregate("Item1", "Item2", "Item3", "Item4");
      IIterator iterator = aggregate.CreateIterator();

      if (iterator.IsDone()) {
         iterator.First();
      }
      while (!iterator.IsDone()) {
         Console.WriteLine(iterator.CurrentItem());
         iterator.Next();
      }

      Console.ReadKey();
   }
}

.Net 内置了迭代器模式, 也称之为枚举器模式, 对应的接口类型为:

/// IEnumerator 对应 Iterator
public interface IEnumerator {

   object Current;

   bool MoveNext();

   void Reset();

}

/// IEnumerable 与  Aggregate 对应
public interface IEnumerable {

   IEnumerator GetEnumerator();

}

.Net 基础类库之中, 有很多类实现这两个接口, 比如: ArrayList, List, Collection, Hashtable 等。