【设计模式】迭代器

来源:互联网 发布:c语言运算符号优先级 编辑:程序博客网 时间:2024/06/07 17:01

迭代器,应该都不陌生了,STL就有提供。

迭代器模式,就是为了对于聚合对象做遍历用,从而隔离具体聚合对象和其访问者。访问者不需要知道聚合对象内部实现,也可以不用跟直接跟聚合对象打交道。

对于不同的聚合对象,一般都用统一的接口(多态迭代),从而方便使用者。

迭代器的实现相对也比较简单,但是有一些重复读,跳读等问题。这个后面在研究研究。

/*************************************************************************** *  * Copyright (c) 2013 itegel.com, Inc. All Rights Reserved *  **************************************************************************/  /** * @file test_iterator.cpp * @author itegel * @date 2013/05/31 10:32:58 * @brief  *   **/#include <vector>#include <iostream>using namespace std;template <class Item>class Iterator{    public:        virtual void First() = 0;        virtual void Next() = 0;        virtual bool IsDone() const = 0;        virtual Item Current() const = 0;    protected:        Iterator(){};};template <class Item>class VectorIterator : public Iterator<Item>{    public:        VectorIterator(const vector<Item> * vec):_vec(vec){            _current = 0;        }        virtual ~VectorIterator(){}        virtual void First(){            _current = 0;        }        virtual void Next(){            _current++;        }        virtual bool IsDone() const {            return (unsigned int)_current >= _vec->size();        }        virtual Item Current() const {            return (*_vec)[_current];        }    private:        const vector<Item> * _vec;        int _current;};int main(){    vector<int> test_vec;    test_vec.push_back(10);    test_vec.push_back(1);    test_vec.push_back(12);    test_vec.push_back(11);    test_vec.push_back(13);    test_vec.push_back(4);    test_vec.push_back(9);    VectorIterator<int> *v_iter = new VectorIterator<int>(&test_vec);    for (; !v_iter->IsDone(); v_iter->Next()){        cout<<v_iter->Current()<<endl;    }    return 0;}

当然这个只是一个demo,vector已经提供了迭代器,实际中标准容器都有相应的迭代器^_^

后面再看看余下的问题。


原创粉丝点击