迭代器模式
来源:互联网 发布:stc89c52单片机驱动 编辑:程序博客网 时间:2024/06/07 09:25
作用:是对一个集合的遍历。
JDK,中Collection,的iterator遍历,就是该模式典型例子。
该模式(例举List),首先不会暴露内部结构(我们不知道list内部的结构),可以透明的访问,比如get(index)等。
迭代器角色:
public interface Iterator{ public boolean hasNext(); public Object next();}
具体迭代器角色:
public class concreteIterator implement Iterator{ private List list = null; private int index; public ConcreteIterator(List list){ super(); this.list = list; } public void hasNext(){ if(index>=list.getSize()){ return false; }else{ return true; } } public Object next(){ Object object = list.get(index); index++; return object; }}
public interface List{ public void add(Object object); public void get(int index); public Iterator iterator(); public int getSize();}
public class ConcreteList implement List{ private Object[] list; private int size=0; private int index=0; public ConcreteList(){ index = 0; size = 0; list = new Object[100]; } public void add(Object obj){ list[index++] = obj; size++; } public Object get(int index){ return list(index); } public int getSize(){ return size; } public Iterator iterator(){ return ConcreteIterator(this); }}
上面就是list 迭代器的实现。
我们可以自定义迭代器,去以自己想要的方式去遍历。
缺点:就是比较繁琐。
我们一般写一个自己的集合,就需要提供相应的迭代器。
0 0
- 行为模式-迭代器模式
- 设计模式-迭代器模式
- 设计模式 迭代器模式
- 设计模式-迭代器模式
- 设计模式--迭代器模式
- 【设计模式】迭代器模式
- 设计模式-迭代器模式
- 设计模式- 迭代器模式
- 设计模式 - 迭代器模式
- 设计模式:迭代器模式
- 行为模式-迭代器模式
- 设计模式 - 迭代器模式
- 设计模式-迭代器模式
- 设计模式--迭代器模式
- 设计模式---迭代器模式
- 设计模式---迭代器模式
- 【设计模式】迭代器模式
- 设计模式 迭代器模式
- 使用浏览器查看Android SQLite数据库-Android Debug Database用法
- 与spring结合的策略模式
- Designing Data-Intensive Applications(设计数据密集应用)- O'Reilly 2017 读书笔记
- jQuery 判断页面元素是否存在的代码
- python使用HTMLParser和BeautifulSoup解析网页
- 迭代器模式
- Codeforces Round #370 (Div. 2) D. Memory and Scores —— DP
- ViewDragHelper 深入解析
- 单例模式中为什么用枚举更好?
- 关于web前端学习
- 斯坦福 cs106A Assignment4
- CSU~1336: Interesting Calculator(spfa)
- SVN有冲突
- vs2015加载项目失败