迭代器模式提供一种方法顺序访问聚合对象中各个元素,而又不暴露该对象的内部表示。
迭代器模式已经在编程语言内部中实现了。
样例见代码。code example
例如我们听音乐的app中的播放列表。我们可以选择顺序播放,或者随机播放。
A collection is only useful when it’s provides a way to access its elements without exposing its internal structure. The iterators bear this responsibility.
So any time, we have collection of objects and clients need a way to iterate over each collection elements in some proper sequence, we must use iterator pattern to design the solution.
当要遍历集合内部对象的时候就可以使用迭代器模式。
实现可以参考Java中的List抽象类中会创建一个Iterator, Iterator接口中有抽象方法例如hasNext(),next(),remove.
ArrayList继承List,其中会创建一个ArrayItr.
privatestaticclassArrayItr<E> implementsIterator<E> {
privateintcursor;
privatefinalE[] a;
ArrayItr(E[] a) {
this.a = a;
}
@OverridepublicbooleanhasNext() {
returncursor < a.length;
}
@OverridepublicEnext() {
inti = cursor;
if (i >= a.length) {
thrownewNoSuchElementException();
}
cursor = i + 1;
returna[i];
}
}