迭代器模式

简介

迭代器模式,提供一种方法访问聚合对象中的各个元素,而不需要暴露它的内部实现。迭代器模式在stl的容器中被普遍使用,实际开发中自己实现一个迭代器并不多见,使用居多。

UML类图

示例

以数组为例,来说明实现迭代器模式,使用了模板类,可以实例化多种类型的数组。
迭代器和聚合对象相关类,iterator.h

#ifndef ITERATOR_H
#define ITERATOR_H

const int nSize = 10;
template  class CAggregate;

template
class CIterator
{
public:
    CIterator(){m_nIndex = 0;}
    virtual void First() = 0;
    virtual void Next() = 0;
    virtual bool HasNext() = 0;
    virtual T GetCurrentItem() = 0;
protected:
    int m_nIndex;
};
template
class CConcreteIterator:public CIterator
{
public:
    CConcreteIterator(CAggregate* pAggregate)
    {
        m_pAggregate = pAggregate;
    }
    void First()
    {
        m_nIndex = 0;
    }
    void Next()
    {
        ++m_nIndex;
    }
    bool HasNext()
    {
        if(m_nIndex < nSize && m_nIndex >= 0)
            return true;
        return false;
    }
    T GetCurrentItem()
    {
        return m_pAggregate->GetItem(m_nIndex);
    }
private:
    CAggregate* m_pAggregate; 
};
template 
class CAggregate
{
public:
    CAggregate(){m_nCurIndex = 0;}
    virtual CIterator* CreateIterator() = 0;
    virtual T GetItem(const int nIndex) = 0;
    virtual void Add(T t) = 0;
protected:
    T m_arralist[nSize];
    int m_nCurIndex;
};

template 
class CConcreteAggregate:public CAggregate
{
public:
    CConcreteAggregate(){}
    CIterator* CreateIterator()
    {
        return new CConcreteIterator(this);
    }
    T GetItem(const int nIndex)
    {
        return m_arralist[nIndex];
    }
    void Add(T t)
    {
        m_arralist[m_nCurIndex] = t;
        ++m_nCurIndex;
    }
};
#endif

客户端调用,main.cpp

#include 
#include "iterator.h"

using namespace std;
#define SAFE_DELETE(p) if(p){delete (p); (p) = NULL;}
int main(int argc, char* argv[])
{
    CAggregate* pAggregate = new CConcreteAggregate;
    for(int i = 0; i < nSize; ++ i)
    {
        pAggregate->Add(i);
    }

    CIterator* pIter = pAggregate->CreateIterator();
    for( ; pIter->HasNext() ;)
    {
        cout<GetCurrentItem()<Next();
    }
    SAFE_DELETE(pIter);
    SAFE_DELETE(pAggregate);
     return 0;
}

你可能感兴趣的:(c++,设计模式)