Java中的迭代器模式

来源:互联网 发布:mac电脑数据恢复 编辑:程序博客网 时间:2024/06/06 18:04


迭代器模式的本质:

        分离集合对象的遍历行为,抽象出单独的迭代器来负责。

        优点明显:既不暴露内部的数据结构,又可以让外部透明地访问内部的数据。

 

启发:

        不论集合内部的数据如何表示,都可以通过iterator接口完成对内部数据的遍历和访问;这是怎么做到的?

        如下面的例子:其实也没那么难,如果本体不能满足Iterator的需要,可以适当地在本体中增加对应接口。

 

我们还是创建一个实例来说明该特例:

interface Iterator<T>{T next();boolean hasNext();}class MyStack<T>{//内部会有一个类来实现上述的Iterator接口;private Object[] elements;private int size = 0;private int capacity;class StackIterator implements Iterator{private MyStack ms;private int nextIndex;public StackIterator(MyStack ms){this.ms = ms;nextIndex = ms.getSize();//System.out.println("nextIndex = "+nextIndex);}public T next(){if(nextIndex >= 0)return (T)pick(--nextIndex);elsereturn null;}public boolean hasNext(){return (nextIndex != 0);}}public MyStack(int size){capacity = size;elements = new Object[size];}public void push(T element){  //为简单,考虑最简情况;elements[size++] = element;}public T pop(){return (T) elements[--size];}public int getSize(){ return size;  }public boolean isEmpty(){return (size==0);}public Iterator iterator(){return new StackIterator(this);}public T pick(int index){return (T)elements[index];}}public class diedaiqi{public static void main(String args[]){MyStack<String> ms = new MyStack<String>(10);ms.push("abc");ms.push("123");Iterator ii = ms.iterator();while(ii.hasNext()){System.out.println(ii.next());}}}

上述的实现中为了配合next的操作,在Stack类中增加pick()方法;上面的方法只提供了nexthasNext()这两种最常用的方法,没有提供其他更复杂的方法,但已经能够说明迭代器的基本工作原理了。



0 0
原创粉丝点击