Iterator模式C++实现

原文链接

Iterator模式C++实现

#include <iostream>
using namespace std;
typedef int DATA;
class Iterator;

// 容器的抽象基类
class Aggregate {
public:
    virtual ~Aggregate(){}

    virtual Iterator* CreatIterator(Aggregate *pAggregate)=0;
    virtual int GetSize()=0;
    virtual DATA GetItem(int nIndex)=0;
};

// 迭代器的抽象基类
class Iterator {
public:
    virtual ~Iterator(){}

    virtual void First()=0;
    virtual void Next()=0;
    virtual bool IsDone()=0;
    virtual DATA CurrentItem()=0;
};

// 一个具体的容器类
class ConcreteAggregate : public Aggregate {
public:
    ConcreteAggregate(int nSize);
    virtual ~ConcreteAggregate();

    virtual Iterator* CreatIterator(Aggregate *pAggregate);
    virtual int GetSize();
    virtual DATA GetItem(int nIndex);
private:
    int m_nSize;
    DATA *m_pData;
};

// 访问ConcreteAggregate容器的迭代器类
class ConcreteIterator : public Iterator {
public:
    ConcreteIterator(Aggregate* pAggreagte);
    virtual ~ConcreteIterator(){}

    virtual void First();
    virtual void Next();
    virtual bool IsDone();
    virtual DATA CurrentItem();
private:
    Aggregate *m_pConcreteAggregate;
    int m_nIndex;
};

// ConcreteAggregate
ConcreteAggregate::ConcreteAggregate(int nSize) : m_nSize(nSize), m_pData(NULL) {
    m_pData = new DATA[m_nSize];
    for (int i = 0; i < m_nSize; ++i) {
        m_pData[i] = i;
    }
}
ConcreteAggregate::~ConcreteAggregate() {
    delete [] m_pData;
    m_pData = NULL;
}
Iterator* ConcreteAggregate::CreatIterator(Aggregate *pAggregate) {
    return new ConcreteIterator(this);
}
int ConcreteAggregate::GetSize() {
    return m_nSize;
}
DATA ConcreteAggregate::GetItem(int nIndex) {
    if (nIndex < m_nSize) {
        return m_pData[nIndex];
    }
    else {
        return -1;
    }
}

// ConcreteIterator
ConcreteIterator::ConcreteIterator(Aggregate* pAggreagte) : m_pConcreteAggregate(pAggreagte), m_nIndex(0) {
}
void ConcreteIterator::First() {
    m_nIndex = 0;
}
void ConcreteIterator::Next() {
    if (m_nIndex < m_pConcreteAggregate->GetSize()) {
        ++m_nIndex;
    }
}
bool ConcreteIterator::IsDone() {
    return m_nIndex == m_pConcreteAggregate->GetSize();
}
DATA ConcreteIterator::CurrentItem() {
    return m_pConcreteAggregate->GetItem(m_nIndex);
}

int main() {
    Aggregate * pAggregate = new ConcreteAggregate(10);

    for (Iterator * pIterator = new ConcreteIterator(pAggregate); !pIterator->IsDone(); pIterator->Next()) {
        cout << pIterator->CurrentItem() << endl;
    }
    return 0;
}
上一篇:mongo聚合查询


下一篇:关于.NET中迭代器的实现以及集合扩展方法的理解