迭代器模式

2018-08-19  本文已影响0人  hankchang

迭代器模式

示例

迭代器模式.png
迭代器模式封装.png

UML

UML.png
class Iterator {
  constructor(container) {
    this.list = container.list
    this.index = 0
  }
  next() {
    if (this.hasNext()) {
      return this.list[this.index++]
    }
    return null
  }
  hasNext() {
    if (this.index >= this.list.length) {
      return false
    }
    return true
  }
}
class Container {
  constructor(list) {
    this.list = list
  }
  getIterator() {
    return new Iterator(this)
  }
}
const arr = [1, 2, 3, 4, 5, 6]
const container = new Container(arr)
const iterator = new Iterator(container)

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

场景

jQuery each

jQueryeach.png

ES6 iterator

ES6.png

设计原则验证

上一篇 下一篇

猜你喜欢

热点阅读