迭代器模式

来源:互联网 发布:mac电磁阀官网 编辑:程序博客网 时间:2024/06/05 18:24

提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。当你需要访问一个聚集对象,而且不管这些对象是什么都需要遍 历的时候,就应该考虑用迭代器模式。同时需要对聚集有多种方式遍历时,可以考虑用迭代器模式。为遍历不同的聚集结构提供如开始、下一个、是否结束、当前哪 一项等统一接口。迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集 合内部的数据。

#include <iostream>#include <vector>#include <string>using namespace std;class Iterator{public:    virtual ~Iterator(){}    virtual string first()=0;    virtual string next()=0;    virtual string getCur()=0;    virtual bool isend()=0;};class Aggregate{public:    virtual ~Aggregate(){}    virtual int count()=0;    virtual void push(const string&s)=0;    virtual string pop(const int &index)=0;    virtual Iterator *createIterator()=0;};class ConcreteIterator:public Iterator{public:    ConcreteIterator(Aggregate*agg=NULL):m_agg(agg),m_nCurrent(0){}    string first(){return m_agg->pop(0);}    string next(){        string tmpStr;        m_nCurrent++;        if(m_nCurrent<m_agg->count())            tmpStr=m_agg->pop(m_nCurrent);        return tmpStr;    }    string getCur(){        return m_agg->pop(m_nCurrent);    }    bool isend(){        return (m_nCurrent>=m_agg->count())?true:false;    }private:    Aggregate *m_agg;    int m_nCurrent;};class ConcreteAggregate:public Aggregate{public:    ConcreteAggregate():m_iterator(NULL){        m_vtr.clear();    }    ~ConcreteAggregate(){        if(m_iterator!=NULL){            delete m_iterator;            m_iterator=NULL;        }    }    int count(){return m_vtr.size();}    void push(const string&s){        m_vtr.push_back(s);    }    string pop(const int &index){        string tmpstr;        if(index<m_vtr.size())            tmpstr=m_vtr[index];        return tmpstr;    }    Iterator *createIterator(){        if(m_iterator==NULL)            m_iterator=new ConcreteIterator(this);        return m_iterator;    }private:    vector<string>m_vtr;    Iterator *m_iterator;};int main(){    ConcreteAggregate *newConcrete=new ConcreteAggregate;    if(newConcrete!=NULL)    {        newConcrete->push("one");        newConcrete->push("two");        newConcrete->push("three");    }    Iterator*it=newConcrete->createIterator();    //    ConcreteIterator *it=newConcrete->createIterator();    if(it!=NULL)    {        while(!it->isend())        {            cout<<"newConcrete:"<<it->getCur()<<endl;            it->next();        }    }    return 0;}




原创粉丝点击