[C++设计模式] iterator 迭代器模式

来源:互联网 发布:网络黄牛是什么意思 编辑:程序博客网 时间:2024/06/05 20:29

迭代器模式定义:提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该对象。

迭代器分内部迭代器和外部迭代器,内部迭代器与对象耦合紧密,不推荐使用。外部迭代器与聚合容器的内部对象松耦合,推荐使用。
迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集 合内部的数据。而且,可以同时
定义多个迭代器来遍历,互不冲突。

对于迭代器,参考STL迭代器,只需要使用具体容器的迭代器就可以遍历该容器内的聚合对象,也可以借助迭代器实现对象的诸如添加、删除和调用。


1.迭代器角色(Iterator):迭代器角色负责定义访问和遍历元素的接口。
2.具体迭代器角色(Concrete Iterator):具体迭代器角色要实现迭代器接口,并要记录遍历中的当前位置。
3.集合角色(Aggregate):集合角色负责提供创建具体迭代器角色的接口。
4.具体集合角色(Concrete Aggregate):具体集合角色实现创建具体迭代器角色的接口——这个具体迭代器角色于该集合的结构相关。

C++迭代器模式(与STL接口保持一致)代码:

#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>{    ConcreteAggregate<Item> * aggr;    int cur;public:    ConcreteIterator(ConcreteAggregate<Item>*a):aggr(a),cur(0){}    virtual void first()    {        cur=0;    }    virtual void next()    {        if(cur<aggr->getLen())            cur++;    }    virtual Item* currentItem()    {        if(cur<aggr->getLen())            return &(*aggr)[cur];        else            return NULL;    }    virtual bool isDone()    {        return (cur>=aggr->getLen());    }};template<class Item>class Aggregate{public:    virtual Iterator<Item>* createIterator()=0;    virtual ~Aggregate(){}};template<class Item>class ConcreteAggregate:public Aggregate<Item>{    vector<Item >data;public:    ConcreteAggregate()    {        data.push_back(1);        data.push_back(2);        data.push_back(3);    }    virtual Iterator<Item>* createIterator()    {        return new ConcreteIterator<Item>(this);    }    Item& operator[](int index)    {        return data[index];    }    int getLen()    {        return data.size();    }};int main(){    Aggregate<int> * aggr =new ConcreteAggregate<int>();    Iterator<int> *it=aggr->createIterator();    for(it->first();!it->isDone();it->next())    {        cout<<*(it->currentItem())<<endl;    }    delete it;    delete aggr;    return 0;}


0 0
原创粉丝点击