1. 程式人生 > 實用技巧 >設計模式-迭代器模式

設計模式-迭代器模式

定義

迭代器模式提供了一種方法,順序訪問集合物件中的元素,而又不暴露該物件的內部實現。
將集合中遍歷元素的操作抽象出來,這樣符合面向物件設計原則中的單一職責原則,我們要儘可能的分離這些職責,用不同的類去承擔不同的責任,避免一個類中承擔太多的責任。迭代器模式就是用迭代器類來承擔遍歷集合元素的責任。

自己實現一個迭代器:

    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);
        }
    }