[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
- 设计模式 -- Iterator(迭代器)
- Iterator(迭代器)设计模式
- Iterator 迭代器设计模式
- Iterator 迭代器设计模式
- 设计模式----Iterator(迭代器)模式
- 设计模式--迭代器模式(Iterator)
- [设计模式]Iterator迭代器模式
- 设计模式 迭代器模式 Iterator
- 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)
- 设计模式(C#)之迭代器模式(Iterator Pattern)
- 设计模式(C#)之迭代器模式(Iterator Pattern)
- 设计模式--Iterator模式
- 设计模式---Iterator模式
- 设计模式--Iterator 模式
- 【设计模式】Iterator模式
- 设计模式之Iterator (迭代器)
- 设计模式之:Iterator迭代器
- 设计模式之Iterator迭代器
- hdoj 2577 How to Type 【坑】
- 不同数据库标志符长度限制总结
- GCD研究
- unknown encoding: cp65001错误
- Axis2.0客户端添加base认证
- [C++设计模式] iterator 迭代器模式
- 两个java对象相同属性赋值
- 【玩转cocos2d-x之二十】从CCObject看cocos2d-x的内存管理机制
- 栈 poj1068 Parencodings
- CentOS 7.0关闭默认防火墙firewalld,使用iptables
- 【玩转cocos2d-x之二十一】多线程和同步01-pthread库
- android类之Pattern
- H264视频的sps和pps解析和哥伦布编码
- hdu 1022 Train Problem I