迭代器模式
来源:互联网 发布:sql server数据库知识 编辑:程序博客网 时间:2024/06/01 16:55
定义:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
体会:迭代器在STL里面用到很多,vector, list都有迭代器,用的时候,我并不关心里面是怎么实现的,我只是循环地读取里面的值就可以了。如果后面我把存数据的集合由vector改成了list,对外面来说没有影响。因为外面只用到了迭代器。
实现:
class Iterator{public: virtual void first() = 0; virtual void last() = 0; virtual void next() = 0; virtual void prev() = 0;};using namespace std;template <class T>class MyVector : public vector<T>, public Iterator{public: MyVector() : vector<T>() { m_index = 0; }public: void add(T value) { vector<T>::push_back(value); }public: void first() { m_index = 0; } void last() { m_index = vector<T>::size() - 1; } void next() { if (m_index < vector<T>::size() - 1) { m_index++; } } void prev() { if (m_index > 0) { m_index--; } } T current() { return vector<T>::at(m_index); }private: size_type m_index;};测试代码如下:
MyVector<QAction *> m_List; QAction *ac1 = new QAction("ac1", this); m_List.add(ac1); QAction *ac2 = new QAction("ac2", this); m_List.add(ac2); QAction *ac3 = new QAction("ac3", this); m_List.add(ac3); qDebug() << m_List.current()->text(); m_List.next(); qDebug() << m_List.current()->text(); m_List.last(); qDebug() << m_List.current()->text(); m_List.prev(); qDebug() << m_List.current()->text(); m_List.first(); qDebug() << m_List.current()->text();
输出值为:
"ac1"
"ac2"
"ac3"
"ac2"
"ac1"
0 0
- 行为模式-迭代器模式
- 设计模式-迭代器模式
- 设计模式 迭代器模式
- 设计模式-迭代器模式
- 设计模式--迭代器模式
- 【设计模式】迭代器模式
- 设计模式-迭代器模式
- 设计模式- 迭代器模式
- 设计模式 - 迭代器模式
- 设计模式:迭代器模式
- 行为模式-迭代器模式
- 设计模式 - 迭代器模式
- 设计模式-迭代器模式
- 设计模式--迭代器模式
- 设计模式---迭代器模式
- 设计模式---迭代器模式
- 【设计模式】迭代器模式
- 设计模式 迭代器模式
- GDB使用入门
- Android:对service的一点理解1
- 蓝桥杯历届真题 九宫重排 康拓展开式
- 今天学函数的一些小程序
- mac graphviz fontname lable miss
- 迭代器模式
- Double Checked Locking 模式 -- 单例实现的多线程版本
- 查看MicroSoft Help
- 半自动化安装Ganglia
- 从Delphi REST服务器返回图像并显示在浏览器中
- 黑马程序员 java高新技术笔记(二)
- java之监听器详解
- win7 32/64bit VS2010 OpenCV 2.4.9 环境配置
- Atlas源码学习(一)