迭代器设计模式广泛用于集合中的遍历
这里主要用到了内部类
以下是简化的的一个迭代器的设计模式
1.Iterator接口
public interface Iterator<E> { boolean hasNext(); E next(); }
public class Outer { private Object[] item; private int size = 0; public Outer(int n) { if(n<=0){ System.out.println("越界了"); } item = new Object[n]; } public void add(Object object){ item[size++] = object; } public Iterator<Object> iterator(){ return new Iter(); } public class Iter implements Iterator<Object>{ int current = 0; @Override public boolean hasNext() { return current < size; } @Override public Object next() { if(current >= size){ return null; } return item[current++]; } } }
public static void main(String[] args){ Outer outer = new Outer(10); outer.add(new Object()); outer.add(new Object()); outer.add(new Object()); outer.add(new Object()); outer.add(new Object()); Iterator<Object> iterator = outer.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next().toString()); } }
java.lang.Object@6ea4b78b java.lang.Object@51da6868 java.lang.Object@1d8806f7 java.lang.Object@189ddde9 java.lang.Object@1d1d2b8
原文地址:http://blog.csdn.net/liu00614/article/details/39323739