迭代器设计模式广泛用于集合中的遍历
这里主要用到了内部类
以下是简化的的一个迭代器的设计模式
1.Iterator接口
public interface Iterator<E> { boolean hasNext(); E next(); }
2.内部类
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++]; } } }
3.测试
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()); } }
输出结果
[email protected] [email protected] [email protected] [email protected] [email protected]
很简单却很使用的一个设计模式,但是前提是要把内部类了解一遍
时间: 2024-10-16 03:41:23