迭代器模式(Iterator)
来源:互联网 发布:少年啊bigbang知乎 编辑:程序博客网 时间:2024/04/30 08:19
顾名思义,迭代器模式就是顺序访问聚集中的对象,一般来说,集合中非常常见,如果对集合类比较熟悉的话,理解本模式会十分轻松。这句话包含两层意思:一是需要遍历的对象,即聚集对象,二是迭代器对象,用于对聚集对象进行遍历访问。
实现代码:
两个接口:public interface Collection {Iterator iterator();/* 取得集合元素 */Object get(int i);/* 取得集合大小 */int size();}
public interface Iterator {// 前移Object previous();// 后移Object next();boolean hasNext();// 取得第一个元素Object first();}
两个实现:
public class DataCollection implements Collection {public String string[] = { "A", "B", "C", "D", "E" };@Overridepublic Iterator iterator() {return new DataIteratorImpl(this);}@Overridepublic Object get(int i) {return string[i];}@Overridepublic int size() {return string.length;}}
public class DataIteratorImpl implements Iterator {private Collection collection;private int pos = -1;public DataIteratorImpl(Collection collection) {this.collection = collection;}@Overridepublic Object previous() {if (pos > 0) {pos--;}return collection.get(pos);}@Overridepublic Object next() {if (pos < collection.size() - 1) {pos++;}return collection.get(pos);}@Overridepublic boolean hasNext() {if (pos < collection.size() - 1) {return true;} else {return false;}}@Overridepublic Object first() {pos = 0;return collection.get(pos);}}测试类:
public class Test {public static void main(String[] args) {Collection collection = new DataCollection();Iterator it = collection.iterator();while (it.hasNext()) {System.out.println(it.next());}}}输出:A B C D E
其实JDK中各个类也都是这些基本的东西,加一些设计模式,再加一些优化放到一起。
0 0
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- Iterator(迭代器)模式
- 迭代器模式(Iterator)
- 迭代器(Iterator)模式
- 迭代器模式(Iterator)
- Iterator(迭代器模式)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- ATL字符串转换宏
- 读书笔记: More Effective C++ 基础议题,条款1到条款4
- 云服务器试用小计-centos
- 搭建一个应用程序框架-做点什么
- stren 和sizeof的区别
- 迭代器模式(Iterator)
- fork()两次不同返回值的实现
- 反转单向链表
- 汇聚互联网段地址api 的使用
- java常用API
- AE开发,有几个点,已知X,Y坐标,如何在AxMapControl中显示这些点
- exec函数族理解
- 博客新人类
- 黑马程序员——多线程