迭代器模式

来源:互联网 发布:c语言完全手册pdf下载 编辑:程序博客网 时间:2024/04/30 20:02

UML类图


上图:

    Iterator:定义迭代器访问和遍历元素的接口;
    ConcreteIterator:具体迭代器的实现;
    Aggregate:定义的容器,创建相应迭代器对象的接口;
    concreteAggregate:具体的容器实现创建相应迭代器的接口,该操作返回ConcreteIterator的一个适当的实例。

使用场合

    访问一个聚合对象的内容而无需暴露它的内部表示;
    支持对聚合对象的多种遍历(从前到后,从后到前);
    为遍历不同的聚合结构提供一个统一的接口,即支持多态迭代。

作用

    它支持以不同的方式遍历一个聚合,甚至都可以自己定义迭代器的子类以支持新的遍历;
    迭代器简化了聚合的接口,有了迭代器的遍历接口,聚合本身就不再需要类似的遍历接口了。这样就简化了聚合的接口;
    在同一个聚合上可以有多个遍历,每个迭代器保持它自己的遍历状态;因此,我们可以同时进行多个遍历;

示例

// testk.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <vector>using namespace std;template<class Item>class Iterator{public:virtual void first() = 0;virtual void next() = 0;virtual bool isDone() = 0;virtual Item* currentItem() = 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];elsereturn NULL;}virtual bool isDone(){return (cur >= aggr->getLen());}};template<class Item>class Aggregate{public:virtual Iterator<Item>* createIterator() = 0;virtual ~Aggregate(){}virtual void append(Item v) = 0;};template<class Item>class concreteAggregate: public Aggregate<Item>{vector<Item> data;public:virtual Iterator<Item>* createIterator(){return new concreteIterator<Item>(this);}int getLen(){return data.size();}Item& operator[](int index){return data[index];}void append(Item v){data.push_back(v);}};//Resource acquisition is initializationtemplate<class Item>class IteratorPtr{public:IteratorPtr(Iterator<Item>* pIterator):  m_pIterator(pIterator) {}    ~IteratorPtr(){delete m_pIterator;}Iterator<Item> *operator->(){return m_pIterator;}Iterator<Item>* operator*(){return *m_pIterator;}private:IteratorPtr(const Iterator<Item> &);IteratorPtr &operator=(const IteratorPtr&);void *operator new (size_t size);void operator delete(void*);Iterator<Item> *m_pIterator;};int main(int argc, char* argv[]){Aggregate<int> *aggr = new concreteAggregate<int>();aggr->append(3);aggr->append(4);aggr->append(5);//Iterator<int> *it = aggr->createIterator();IteratorPtr<int> iter(aggr->createIterator());for(iter->first(); !iter->isDone(); iter->next()){cout <<*(iter->currentItem())<<endl;}delete aggr;return 0;}




0 0
原创粉丝点击