iT邦幫忙

2023 iThome 鐵人賽

DAY 20
0
自我挑戰組

設計模式系列 第 20

Day20 - 迭代器模式(Iterator pattern)

  • 分享至 

  • xImage
  •  

介紹
迭代器模式提供順序訪問容器內的元素,而不暴露該容器內部實作。

C++範例

#include <iostream>
#include <string>
#include <vector>

// 抽象迭代器
class Iterator
{
public:
    virtual ~Iterator() {}
    virtual int First() = 0;
    virtual int Next() = 0;
    virtual int Current() = 0;
    virtual bool IsEnd() = 0;
};

// 抽象聚合類: 要被迭代的容器
class Aggregate
{
public:
    virtual ~Aggregate() {}
    virtual void Push(int i) = 0;
    virtual int Pop(size_t index) = 0;
    virtual size_t Size() const = 0;
    virtual Iterator *CreateIterator() = 0;
};

class ConcreteIterator : public Iterator
{
public:
    ConcreteIterator(Aggregate *aggr) : m_aggr(aggr), m_index(0)
    {
    }

    ~ConcreteIterator()
    {
    }

    virtual int First() override
    {
        if (m_aggr->Size() == 0)
            return -1;
        return m_aggr->Pop(0);
    }

    virtual int Next() override
    {
        m_index++;
        if (m_index >= m_aggr->Size())
            return -1;
        return m_aggr->Pop(m_index);
    }

    virtual int Current() override
    {
        if (m_index >= m_aggr->Size())
            return -1;
        return m_aggr->Pop(m_index);
    }

    virtual bool IsEnd() override
    {
        return m_index >= m_aggr->Size() || m_index < 0;
    }

private:
    Aggregate *m_aggr;
    size_t m_index;
};

class ConcreteAggregate : public Aggregate
{
public:
    ConcreteAggregate()
    {
    }
    ~ConcreteAggregate()
    {
    }

    void Push(int i) override
    {
        return m_data.push_back(i);
    }

    int Pop(size_t index) override
    {
        if (index >= m_data.size())
            return -1;
        return m_data[index];
    }

    size_t Size() const override
    {
        return m_data.size();
    }

    virtual Iterator *CreateIterator()
    {
        return new ConcreteIterator(this);
    }

private:
    std::vector<int> m_data;
};

int main()
{
    Aggregate *aggr = new ConcreteAggregate();
    aggr->Push(1);
    aggr->Push(2);
    aggr->Push(3);

    Iterator *iter = aggr->CreateIterator();

    for (iter->First(); !iter->IsEnd(); iter->Next())
    {
        std::cout << iter->Current() << std::endl;
    }

    return 0;
}

Output:

1
2
3

Ref:
https://blog.csdn.net/naibozhuan3744/article/details/109249815


上一篇
Day19 - 解釋器模式(Interpret pattern)
下一篇
Day21 - 備忘錄模式(Memento pattern)
系列文
設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言