设计模式学习笔记之迭代器模式

来源:互联网 发布:易语言短信轰炸机源码 编辑:程序博客网 时间:2024/04/30 04:28

所谓迭代器模式,即将迭代遍历的方法抽象出来,用一个迭代器类来专门负责迭代遍历。

首先定义迭代器的接口:

package IteratorPolicy;/* * author:Tammy Pi * function:迭代器的接口 */public interface Iterator<T> {public int first();public int next();public boolean isLast();public T getCurrentItem();}

迭代器的实现:

package IteratorPolicy;/* * author:Tammy Pi * function:迭代器的实现类 */public class IteratorImp<T> implements Iterator{private T[] elements = null;private int current = 0;//构造函数public IteratorImp(T[] elements){this.elements = elements;}public int first() {if(elements.length>0){return current = 0;}return -1;}public T getCurrentItem() {if(current==-1){return null;}return elements[current];}public boolean isLast() {if(current+1==elements.length){return true;}return false;}public int next() {if(current+1<elements.length){return current = current + 1;}return -1;}}

其实就是第一个元素,查找下一个元素的坐标,判断是否到最末位置,以及获得当前的元素。

以下是对迭代器的测试:

package IteratorPolicy;/* * author:Tammy Pi * function:测试迭代器的类 */public class TestIterator {public static void main(String[] args){Integer[] a = {2,3,1,5,4};IteratorPolicy.Iterator<Integer> iterator = new IteratorImp<Integer>(a);int tag = iterator.first();if(tag!=-1){do{System.out.print(iterator.getCurrentItem()+" ");}while(iterator.next()!=-1);}}}

JAVA类库中已经包含Iterator了,所以迭代器设计模式目前的学习性大于其实用性。

其实学习时,很难想象这是设计模式之一。

原创粉丝点击