迭代器设计模式在JS中的使用

175 阅读2分钟

迭代器设计模式

本文介绍了迭代器设计模式,此模式的核心是对象暴露了一个遍历对象内部状态的接口;对于ES6而言,这种接口名是固定的,使用者只需按照接口的格式要求实现即可。

1. 定义

一种行为型设计模式,它提供了一种顺序访问集合对象元素的统一方式,而无需暴露集合内部的表示细节

2. 代码实现

在 TypeScript 中,可以使用迭代器设计模式来遍历集合对象:

// 定义一个接口来表示迭代器
interface Iterator<T> {
  hasNext(): boolean;
  next(): T;
}

// 实现一个具体的迭代器类
class ArrayIterator<T> implements Iterator<T> {
  private collection: T[];
  private index: number;

  constructor(collection: T[]) {
    this.collection = collection;
    this.index = 0;
  }

  hasNext(): boolean {
    return this.index < this.collection.length;
  }

  next(): T {
    if (this.hasNext()) {
      const item = this.collection[this.index];
      this.index++;
      return item;
    }
    throw new Error('End of collection.');
  }
}

// 定义一个可迭代的集合类
class MyCollection<T> {
  private items: T[];

  constructor(items: T[]) {
    this.items = items;
  }

  // 返回一个迭代器实例
  getIterator(): Iterator<T> {
    return new ArrayIterator(this.items);
  }
}

// 使用迭代器遍历集合
const collection = new MyCollection<number>([1, 2, 3, 4, 5]);
const iterator = collection.getIterator();

while (iterator.hasNext()) {
  const item = iterator.next();
  console.log(item);
}

在上述示例中,迭代器模式通过定义一个 Iterator 接口和其具体实现类 ArrayIterator,封装了集合对象的遍历行为。MyCollection 类表示一个可迭代的集合,通过 getIterator() 方法返回一个迭代器实例。然后,我们可以使用迭代器来遍历集合中的元素。

3. 特点

  1. 将集合对象的遍历行为封装在迭代器内部,使得客户端代码与集合对象的具体实现解耦
  2. 提供统一的访问方式,无需暴露集合对象的内部结构。
  3. 支持按需惰性加载,只在需要时获取下一个元素。
  4. 可以支持不同类型的集合对象,在迭代器接口中定义通用的遍历方法,具体的实现由迭代器类完成。

4. 总结

通过使用迭代器设计模式,可以更加灵活地处理集合对象的遍历,提高代码的可维护性和扩展性