设计模式-迭代器模式

定义

迭代器模式提供了一种方法,顺序访问集合对象中的元素,而又不暴露该对象的内部实现。
将集合中遍历元素的操作抽象出来,这样符合面向对象设计原则中的单一职责原则,我们要尽可能的分离这些职责,用不同的类去承担不同的责任,避免一个类中承担太多的责任。迭代器模式就是用迭代器类来承担遍历集合元素的责任。

自己实现一个迭代器:

    public interface IMyEnumerable<T>
    {
        IMyEnumerator<T> GetEnumerator();
    }
    public interface IMyEnumerator<T>
    {
        T Current { get; }
        bool MoveNext();
    }
    public class MyEnumerator<T> : IMyEnumerator<T>
    {
        private T[] _items = null;
        private int _index = -1;
        public MyEnumerator(T[] items)
        {
            this._items = items;
        }
        public T Current
        {
            get
            {
                return this._items[this._index];
            }
        }

        public bool MoveNext()
        {
            if (++this._index <= this._items.Length-1)
            {
                return true;
            }
            return false;
        }
    }

MyList:

public class MyList<T> : IMyEnumerable<T>
    {
        private T[] _items = null;
        public MyList(T[] items)
        {
            this._items = items;
        }
        public IMyEnumerator<T> GetEnumerator()
        {
            return new MyEnumerator<T>(this._items);
        }
    }
原文地址:https://www.cnblogs.com/fanfan-90/p/13376037.html