設計模式學習筆記十七——Iterator模式

來源:互聯網
上載者:User
動機:在軟體系統構建過程中,集合對象內部結構常常變化各異。希望在不暴露其內部結構的同時,可以讓客戶程式透明地訪問其中包含的元素,同時這種“透明遍曆”也為“同一種演算法在多種集合對象上進行操作”提供了可能。

情境:在.NET類庫中,IEnumerable即為彙總對象介面,IEnumerator為迭代器介面,通過實現這兩個介面來實現迭代器。

結構

代碼
namespace DesignPattern.Iterator
{
    public class MyCollection : IEnumerable
    {
        int[] items;

        public MyCollection()
        {
            items = new int[5] {1, 2, 3, 4, 5};
        }

        public int[] Items
        {
            get
            {
                return items;
            }
        }

        public IEnumerator GetEnumerator()
        {
            return new MyEnumerator(this);
        }
    }

    public class MyEnumerator : IEnumerator
    {
        int index;
        MyCollection collection;

        public MyEnumerator(MyCollection collection)
        {
            this.collection = collection;
        }
        
        public object Current 
        {
            get
            {
                return collection.Items[index];
            }
        }
            
        public bool MoveNext()
        {
            index ++;
            return (index < collection.Items.GetLength(0));
        }
        
        public void Reset()
        {
            index = -1;
        }
    }
}

namespace DesignPattern.Iterator
{
    public class Client
    {
        public int Sum()
        {
            int sum = 0;

            MyCollection collection = new MyCollection();
            MyEnumerator iterator = new MyEnumerator(collection);

            while (iterator.MoveNext())
            {
                sum += Convert.ToInt32(iterator.Current);
            }

            return sum;
        }
    }
}

 要點
      1、迭代抽象:本模式通過將對彙總對象的訪問和遍曆從彙總對象中分離出來並放入一個迭代器對象中,實現對彙總對象的透明訪問。
      2、迭代多態:為遍曆不同的彙總對象提供一個統一的介面,從而支援同樣的演算法在不同的彙總對象上進行操作。
      3、迭代器的健壯性考慮:遍曆的同時更改迭代器所在的彙總結構,會導致問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.