Sequentially access the elements of a collection without knowing the inner workings of the collection. 提供一种方法以便顺序访问聚合对象之中的各个元素,而又不需暴露该对象的内部表示。
动机:为聚合对象提供访问方法。
适用性:
- 访问一个聚合对象的内容而无需暴露它的内部表示。
- 支持多种遍历方法。
- 为不同的聚合结构,提供统一的遍历接口。
结构和代码示例:
$.each
,_.each
就是遍历的经典方法- see the ES6 iterator object and method
Iterator 可以分为:「内部 Iterator」和「外部 Iterator」,内部主要提供接口然后在内部迭代接口中定义的操作;而外部迭代则是交给用户显式调用迭代器方法来吐出元素进行处理。
实现的时候应该考虑:
- 谁控制迭代:内部 or 外部?
- 谁定义算法?是迭代器的目标:「聚合对象」or 迭代器接口自身。
- 迭代器健壮程度如何,是否会受到聚合对象内部 CURD 操作的影响。
- 是否需要额外的附加迭代功能?比如
skipItem()
等。 - 复合类型的迭代器应该能够迭代 Tree / Graph 类型。
class List {
createIterator(): ListIterator;
}
class SkipList extends List {
createIterator(): SkipListIterator;
}
class Iterator {
next();
first();
isDone();
current();
}
class ListIterator extends Iterator {}
class SkipListIterator extends Iterator {}
效果:
- 支持不同的方式遍历一个聚合。
- 简化了聚合接口,并且在一个接口上能够有多个遍历。