首頁 » 設計模式 » 迭代器(Iterator)

迭代器(Iterator)

作者:

分類:

迭代器(Iterator)

概念

迭代器模式是一種行為型模式,概念是提供容器一個可以依序走訪的功能,想像用鏈結串列的方式訪問每個容器內的物件,而不需要在意容器的結構。

範例

//**************
//* author: cian
//* 20231208
//**************

interface Iterator<T>
{
    T Next();
    bool hasNext();
}

class Item
{
    //Do something...
}

class ConcreteIterator<T> : Iterator<T>
{
    private int currentPosition = 0;
    private readonly T[] collection;

    public ConcreteIterator(T[] Collection)
    {
        collection = Collection;
    }

    public T Next()
    {
        if (HasNext())
        {
            T ret = collection[currentPosition];
            currentPosition++;
            return ret;
        }
        else
        {
            return default;
        }
    }

    public bool HasNext()
    {
        return currentPosition < collection.Length;
    }
}

class NewsApp
{
    static void Main(string[] args)
    {
        Item[] items = new Item[100];
        var aggregate = new ConcreteIterator<Item>(items);

        while (aggregate.HasNext())
        {
            var item = aggregate.Next();
            //item dosomething...
        }
    }
}

結語

在現今的物件導向程式語言中,大多容器都已經實作迭代器,只要foreach就可以遍歷容器內的每個物件,但如果不了解基本的資料結構就很難有更深入的開發。以C#為例,可以搭配LINQ作為遍歷的篩選條件,或是使用yield return來實作迭代方法,玩法十分靈活。

以上為學習過程的問題紀錄

如果文章有誤,歡迎前輩留言請不吝指教。

「cian」的個人頭像

留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *