迭代器模式
来源:互联网 发布:excel怎么去重复数据 编辑:程序博客网 时间:2024/05/21 02:35
1、概念:
迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。
2、角色和职责:
迭代器角色(Iterator):迭代器角色负责定义访问和遍历元素的接口。
具体迭代器角色(Concrete Iterator):具体迭代器角色要实现迭代器接口, 并要记录遍历中的当前位置。
集合角色(Aggregate):集合角色负责提供创建具体迭代器角色的接口。
具体集合角色(Concrete Aggregate):具体集合角色实现创建具体迭代器角色的接口——这个具体迭代器角
3、示例代码:
#include<iostream>using namespace std;typedef int Object;// 模拟对象#define SIZE 5// 抽象的迭代器class MyIterator{public:virtual void First() = 0;// 迭代器的开始位置virtual void Next() = 0;// 迭代器对的下一个位置virtual bool isDone() = 0;// 迭代器的结束位置virtual Object CurrentItem() = 0;// 获取当前对象};// 抽象容器 数组class Aggreagate{public:virtual MyIterator*CreateIteator() = 0;// 创建迭代器virtual Object getItem(int index) = 0;//获取元素virtual int getSize() = 0;// 获取迭代器的大小private:Object objecct[SIZE];};// 具体的迭代器class ContreteIterator :public MyIterator{public:ContreteIterator(Aggreagate *ag){_current_index = 0;_ag = ag;}virtual void First()// 迭代器的开始位置{_current_index = 0;// 让当前 游标位置 回到0}virtual void Next()// 迭代器对的下一个位置{if (_current_index < _ag->getSize()){_current_index++;}}virtual bool isDone()// 迭代器的结束位置{return (_current_index == _ag->getSize());}virtual Object CurrentItem() // 获取当前对象{return _ag->getItem(_current_index);}private:int_current_index;Aggreagate*_ag;};// 具体的集合class ContreteAggreagate :public Aggreagate{public:ContreteAggreagate(){for (int i=0;i<SIZE;i++){objecct[i] = i+100;}}virtual MyIterator*CreateIteator()// 创建迭代器{return new ContreteIterator(this);//让迭代器 持有一个集合的引用}virtual Object getItem(int index)//获取元素{return objecct[index];}virtual int getSize()// 获取迭代器的大小{return SIZE;}private:Object objecct[SIZE];};int main(void){// new 一个集合Aggreagate *ag = new ContreteAggreagate;// 创建一个迭代器MyIterator*it = ag->CreateIteator();for (;(!it->isDone());it->Next()){cout << it->CurrentItem() << " ";}cout << endl;delete ag;delete it;return 0;}
阅读全文
0 0
- 行为模式-迭代器模式
- 设计模式-迭代器模式
- 设计模式 迭代器模式
- 设计模式-迭代器模式
- 设计模式--迭代器模式
- 【设计模式】迭代器模式
- 设计模式-迭代器模式
- 设计模式- 迭代器模式
- 设计模式 - 迭代器模式
- 设计模式:迭代器模式
- 行为模式-迭代器模式
- 设计模式 - 迭代器模式
- 设计模式-迭代器模式
- 设计模式--迭代器模式
- 设计模式---迭代器模式
- 设计模式---迭代器模式
- 【设计模式】迭代器模式
- 设计模式 迭代器模式
- Java的switch分支结构
- tensorflow new/old version function
- [译]Time Series Forecasting with the Long Short-Term Memory Network in Python
- Java的switch语句的注意事项
- adb 命令(部分)
- 迭代器模式
- jsp自定义标签
- 定时任务调度之Timer----入门小试牛刀
- MySQL数据库概述;mysql数据库的安装。MySQL数据库的存储方式概述;SQL概述:结构化查询语言
- Java的switch语句模拟单项选择题
- 网络安全-CSRF跨站伪装脚本注入
- 从linux启动到rootfs的挂载分析
- distutils Unknown MS Compiler version
- Linux基础练习题(8)