首页 > 代码库 > 迭代器模式

迭代器模式

迭代器(Iterator)模式

意图:提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。

主要解决:不同的方式来遍历整个整合对象。

 

代码:

#include <iostream>
#include <vector>
using namespace std;

template<class Item>
class Iterator
{
public:
    virtual void first() = 0;
    virtual void next() = 0;
    virtual Item *currentItem() = 0;
    virtual bool isDone() = 0;
    virtual ~Iterator() {}
};

template<class Item>
class ConcreteAggregate;

template<class Item>
class ConcreteIterator : public Iterator<Item>
{
public:
    ConcreteIterator(ConcreteAggregate<Item> *aggr, int idx=0) :_aggr(aggr), _idx(idx) {}
    virtual void first()
    {
        _idx = 0;
    }

    virtual void next()
    {
        if (!isDone())
            ++_idx;
    }

    virtual  Item *currentItem()
    {
        if (isDone())
            return nullptr;
        return &(*_aggr)[_idx];
    }

    virtual bool isDone()
    {
        return _idx == _aggr->size();
    }
    
private:
    ConcreteAggregate<Item> *_aggr;
    int _idx;
};

template<class Item>
class Aggregate
{
public:
    virtual Iterator<Item> *createIteator() = 0;
    virtual void addItem(const Item &i) = 0;
    virtual ~Aggregate() {}
};

template<class Item>
class ConcreteAggregate : public Aggregate<Item>
{
public:
    ConcreteAggregate()
    {
        _data.clear();
    }
~ConcreteAggregate() { _data.clear(); }
virtual void addItem(const Item &i) override { _data.push_back(i); }
virtual Iterator<Item> * createIteator() override { return new ConcreteIterator<Item>(this); }
Item
& operator[](int idx) { return _data[idx]; }
int size() { return _data.size(); } private: vector<Item> _data; }; void test() { Aggregate<int> *aggr = new ConcreteAggregate<int>(); aggr->addItem(10); aggr->addItem(20); aggr->addItem(30); Iterator<int> *it = aggr->createIteator(); it->first(); while (!it->isDone()) { cout << *(it->currentItem()) << endl; it->next(); }   delete aggr;   delete it; } int main() { test(); cin.get(); return 0; }

 

迭代器模式