Skip to content

Latest commit

History

History
61 lines (40 loc) · 1.73 KB

File metadata and controls

61 lines (40 loc) · 1.73 KB

迭代器模式

定义

迭代器模式提供一种方法顺序访问聚合对象中各个元素,而又不暴露该对象的内部表示。

类图

iterator-pattern

用例

迭代器模式已经在编程语言内部中实现了。

样例见代码。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];
}
}

参考

howtodo-iterator-pattern