介紹
迭代器模式提供順序訪問容器內的元素,而不暴露該容器內部實作。
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