迭代器模式(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
原创粉丝点击