Iterator模式
来源:互联网 发布:绘制地图的软件 编辑:程序博客网 时间:2024/06/15 08:24
Iterator模式用来解决对一个聚合对象的遍历问题。
Aggregate.h
//Aggregate.h#ifndef _AGGREGATE_H_#define _AGGREGATE_H_class Iterator;typedef int Object;class Interator;class Aggregate{public:virtual ~Aggregate();virtual Iterator* CreateIterator() = 0;virtual Object GetItem(int idx) = 0;virtual int GetSize() = 0;protected:Aggregate();private:};class ConcreteAggregate:public Aggregate{public:enum {SIZE = 3};ConcreteAggregate();~ConcreteAggregate();Iterator* CreateIterator();Object GetItem(int idx);int GetSize();protected:private:Object _objs[SIZE];};#endif //~_AGGREGATE_H_Aggregate.cpp
//Aggregate.cpp#include "Aggregate.h"#include "Iterator.h"#include <iostream>using namespace std;Aggregate::Aggregate(){}Aggregate::~Aggregate(){}ConcreteAggregate::ConcreteAggregate(){for (int i = 0; i < SIZE; i++)_objs[i]= i;}ConcreteAggregate::~ConcreteAggregate(){}Iterator* ConcreteAggregate::CreateIterator(){return new ConcreteIterator(this);}Object ConcreteAggregate::GetItem(int idx){if (idx < this->GetSize())return _objs[idx];elsereturn -1;}int ConcreteAggregate::GetSize(){return SIZE;}Iterator.h
//Iterator.h#ifndef _ITERATOR_H_#define _ITERATOR_H_class Aggregate;typedef int Object;class Iterator{public:virtual ~Iterator();virtual void First() = 0;virtual void Next() = 0;virtual bool IsDone() = 0;virtual Object CurrentItem() = 0;protected:Iterator();private:};class ConcreteIterator:public Iterator{public:ConcreteIterator(Aggregate* ag , int idx = 0);~ConcreteIterator();void First();void Next();bool IsDone();Object CurrentItem();protected:private:Aggregate* _ag;int _idx;};#endif //~_ITERATOR_H_Iterator.cpp
//Iterator.cpp#include "Iterator.h"#include "Aggregate.h"#include <iostream>using namespace std;Iterator::Iterator(){}Iterator::~Iterator(){}ConcreteIterator::ConcreteIterator(Aggregate* ag , int idx){this->_ag = ag;this->_idx= idx;}ConcreteIterator::~ConcreteIterator(){}Object ConcreteIterator::CurrentItem(){return _ag->GetItem(_idx);}void ConcreteIterator::First(){_idx = 0;}void ConcreteIterator::Next(){if (_idx < _ag->GetSize())_idx++;}bool ConcreteIterator::IsDone(){return (_idx == _ag->GetSize());}
main.cpp
#include "Aggregate.h"#include "Iterator.h"#include <iostream>using namespace std;int main(){Aggregate* ag = new ConcreteAggregate();Iterator* it = new ConcreteIterator(ag);for (; !(it->IsDone()) ; it->Next()){cout<<it->CurrentItem()<<endl;} return 0;}
0 0
- Iterator模式
- Iterator模式
- Iterator模式
- Iterator模式
- Iterator模式
- Iterator 模式
- Iterator模式
- Iterator模式
- Iterator模式
- Iterator 模式
- Iterator模式
- Iterator模式
- Iterator模式
- Iterator模式
- Iterator 模式
- Iterator模式
- Iterator模式
- Iterator模式
- 【SQL Server备份恢复】数据库恢复:对page header的恢复
- GIS中最小外包矩形(MBR)
- Windows上没法用socket抓MAC层的数据,只能用raw socket抓到IP层及之上的数据.
- 报表
- [项目]ExcelToJsonTool(Excel配置转换Json配置工具)
- Iterator模式
- C#之概述
- 统计学习(3)——k近邻法与kd树
- VNC 设置屏幕分辨率
- 在Android上使用Phonegap的个人经验总结及项目中的优化方案
- 胭脂冷、碎玉楚碟烟花散
- C++Vector用法
- CocosBuilder 完全攻略
- Storm Trident 示例