18.迭代器模式
迭代器模式(Iterator Pattern)的主要目的是提供统一遍历接口,让调用方无需关心集合的内部结构
适合使用迭代器模式的场景
- 需要对外隐藏集合内部实现(数组、链表、树等)
- 希望为自定义数据结构提供统一遍历能力
- 需要支持标准
for...of或迭代协议 - 希望遍历逻辑独立于集合对象本身
自定义可迭代集合
class NameCollection implements Iterable<string> {
constructor(private names: string[]) {}
[Symbol.iterator](): Iterator<string> {
let index = 0;
const data = this.names;
return {
next(): IteratorResult<string> {
if (index < data.length) {
return { value: data[index++], done: false };
}
return { value: undefined, done: true };
},
};
}
}使用示例
const names = new NameCollection(["alice", "bob", "carol"]);
for (const name of names) {
console.log(name);
}