提供一种方法顺序一个聚合对象中各个元素,而又不暴露该对象的内部表示。

  1. class Iterator {
  2. constructor(conatiner) {
  3. this.list = conatiner.list
  4. this.index = 0
  5. }
  6. next() {
  7. if (this.hasNext()) {
  8. return this.list[this.index++]
  9. }
  10. return null
  11. }
  12. hasNext() {
  13. if (this.index >= this.list.length) {
  14. return false
  15. }
  16. return true
  17. }
  18. }
  19. class Container {
  20. constructor(list) {
  21. this.list = list
  22. }
  23. getIterator() {
  24. return new Iterator(this)
  25. }
  26. }
  27. // 测试代码
  28. let container = new Container([1, 2, 3, 4, 5])
  29. let iterator = container.getIterator()
  30. while(iterator.hasNext()) {
  31. console.log(iterator.next())
  32. }

场景例子

  • Array.prototype.forEach
  • jQuery中的$.each()
  • ES6 Iterator

    特点

  • 访问一个聚合对象的内容而无需暴露它的内部表示。

  • 为遍历不同的集合结构提供一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作

    总结

    对于集合内部结果常常变化各异,不想暴露其内部结构的话,但又想让客户代码透明的访问其中的元素,可以使用迭代器模式