设计模式之迭代器模式
来源:互联网 发布:淘宝旺铺全屏代码 编辑:程序博客网 时间:2024/06/13 12:41
迭代器模式
迭代器模式有叫做游标(Cursor)模式,是一种对象行为型模式,它提供一种方法顺序访问一个聚合对象的各个元素,而不需要暴露该对象的内部表示。
定义
提供一种方法顺序访问一个聚合对象的各个元素,而不需要暴露该对象的内部表示。
使用场景
- 访问一个聚合对象的内容而无需暴露它的内部表示。
- 支持对聚合对象的多种遍历。
- 为遍历不同的聚合结构提供一个统一地接口(支持多态迭代)。
结构
实现
public interface Iterator { Object first(); Object next(); Object currentItem(); boolean isDone();}public class ConcreteIterator implements Iterator{ private List<Object> list; private int cursor = 0; public ConcreteIterator(List<Object> list) { this.list = list; } public Object first() { cursor = 0; return list.get(cursor); } public Object next() { cursor++; return list.get(cursor); } public Object currentItem() { return list.get(cursor); } public boolean isDone() { if (cursor >= this.list.size() - 1) { return true; } else { return false; } }}public interface Aggregate { Iterator createIterator();}public class ConcreteAggregate implements Aggregate{ private List<Object> list; public ConcreteAggregate(List<Object> list){ this.list = list; } public Iterator createIterator() { return new ConcreteIterator(this.list); }}
测试
public class Client { public static void main(String[] args) { List<Object> list = new ArrayList<Object>(); list.add(1); list.add(2); Aggregate aggregate = new ConcreteAggregate(list); Iterator it = aggregate.createIterator(); System.out.println(it.currentItem()); while(!it.isDone()){ System.out.println(it.next()); } }}
测试结果:
1
2
迭代器的应用很广泛,常用的JDK的集合类库中有各种各样的迭代器。
0 0
- 设计模式之迭代器模式
- 设计模式之 迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之--迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之-迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式 之 迭代器模式
- 设计模式 之 迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- React-Native-源码分析
- FLV封装格式分析器
- 探究在APP中使用DownloadManager完成下载
- POJ2479 DP
- Android中各种形状
- 设计模式之迭代器模式
- hdu 3555 Bomb(数位DP)
- Hibernate对Oracle中 Clob的使用
- Python日期和时间函数
- 广告轮播图
- React-Native-源码分析二-JSX如何渲染成原生页面(上)
- Reading List
- Android常用控件(能折叠的ListView)--ExpandableListView的使用模仿QQ好友列表
- linux sort