Skip to content

迭代器设计模式 / Iterator

Code

js
// 定义迭代器接口
class Iterator {
  constructor(collection) {
    this.collection = collection;
    this.index = 0;
  }

  next() {
    if (this.index < this.collection.length) {
      const result = this.collection[this.index];
      this.index++;
      return result;
    } else {
      return null;
    }
  }

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

// 定义集合接口
class Collection {
  constructor(items) {
    this.items = items;
  }

  createIterator() {
    return new Iterator(this.items);
  }
}

// 具体的集合实现
class ArrayCollection extends Collection {
  constructor(items) {
    super(items);
  }
}

// 使用示例
const items = [1, 2, 3, 4, 5];
const collection = new ArrayCollection(items);
const iterator = collection.createIterator();

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