和原型模式一样,迭代器模式也基本不需要自己实现了,Java中提供了Iterator接口,可直接实现迭代器。迭代器模式也非常简单,就是为不同的集合统一遍历接口。
这里看下Java中迭代器的实现代码,以ArrayList为例
//ArrayList实现了List接口 public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable //List继承了Collection public interface List<E> extends Collection<E> //Collection继承了Iterable接口 public interface Collection<E> extends Iterable<E> //Iterable只有一个方法,就是返回Iterator对象,Iterator对象的作用就是对List的遍历 public interface Iterable<T> { Iterator<T> iterator(); } //ArrayList里面实现了此iterator()方法,如下 public Iterator<E> iterator() { return new Itr(); } //而Itr是ArrayList的内部类,且这个内部类实现了Iterator接口,实现对ArrayList遍历的具体方法 private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
所以整体结构是这样的。集合类实现了Iterable接口,返回一个Iterator对象,这个对象针对此集合类实现遍历方法。
相关推荐
设计模式的迭代器模式的例子,希望对大家有用~~~~~~~~
设计模式之迭代器模式 设计模式之迭代器模式 设计模式之迭代器模式
迭代器模式Demo
23种设计模式之迭代器模式对迭代器模式进行了简单的介绍,并附带了例子程序,和大家分享
设计模式-迭代器模式(讲解及其实现代码)
迭代器模式的示例代码和文档,学习迭代器模式的参考资料。
一个聚合对象,如一个列表(List)或者一个集合(Set),应该提供一种方法来让别人可以访问它...怎样遍历一个聚合对象,又不需要了解聚合对象的内部结构,还能够提供多种不同的遍历方式,这就是迭代器模式所要解决的问题。
使用composite模式构成二叉树,并用迭代器模式封装访问,前序、中序和后序的遍历。JAVA 编写。 Main中直接运行
迭代器模式demo
C#面向对象设计模式 (行为型模式) Iterator 迭代器模式 视频讲座下载
设计模式--迭代器模式java例子
迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。 那么一般在什么时候才会用迭代器模式呢?当你需要访问一个聚集对象,而且不管这些对象是什么都需要遍历的时候...
java设计模式--迭代器模式,理解这个例子就完全理解迭代器啦
迭代器(Iterator) 用意:可以顺序地访问一个集合中的元素而不必暴露集合中的内部表象。
Headfirst第九章迭代器模式C++实现代码 ,并附加相应的UML类图
迭代器模式(Iterator Pattern)是设计模式中的一种行为模式,它允许顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。迭代器模式提供了一种方法,可以顺序地访问一个聚合对象中的各个元素,而又...
【Java设计模式】(1)迭代器模式Iterator(代码)