您的位置:首页 > 其它

iterator 迭代器模式

2013-12-21 11:51 155 查看
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Iterator;
typedef int Object;
class Interator;

class Aggregate
{
public:
    virtual ~Aggregate(){}
    virtual Iterator *CreateIterator() =0;
    virtual Object GetItem(int index) =0;
    virtual int GetSize() =0;
protected:
    Aggregate(){};
};

class ConcreteAggregate : public Aggregate
{
public:
    enum {SIZE = 3};
    ConcreteAggregate(){
        for (int i = 0; i < SIZE; ++i)
        {
            _obj[i] = (i + 1) * 10;
        }
    }
    ~ConcreteAggregate(){}
    Iterator *CreateIterator();
    Object GetItem(int index)
    {
        if (index < GetSize())
        {
            return _obj[index];
        }
        else
        {
            return -1;
        }
    }
    int GetSize()
    {
        return SIZE;
    }
private:
    Object _obj[SIZE];
};

class Iterator
{
public:
    virtual ~Iterator(){}
    virtual void First() =0;
    virtual void Next() =0;
    virtual bool IsDone() =0;
    virtual Object CurrentItem() =0;
protected:
    Iterator(){}
};

class ConcreteIterator : public Iterator
{
public:
    ConcreteIterator(Aggregate *ag, int index = 0):_ag(ag),_index(index){}
    ~ConcreteIterator(){}
    void First()
    {
        _index = 0;
    }
    void Next()
    {
        if (_index < _ag->GetSize())
            _index++;
    }
    bool IsDone()
    {
        return _index == _ag->GetSize();
    }
    Object CurrentItem()
    {
        return _ag->GetItem(_index);
    }
private:
    Aggregate *_ag;
    int _index;
};

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

int main()
{
    Aggregate *ag = new ConcreteAggregate();
    Iterator *it = ag->CreateIterator();
    for (;!(it->IsDone());it->Next())
    {
        cout<<it->CurrentItem()<<endl;
    }

    delete it;
    delete ag;
    return 0;
} new ConcreteIterator(ag);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: