当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript设计模型Iterator实例解析

JavaScript设计模型Iterator实例解析

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了javascript设计模型iterator实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

iterator pattern是一个很重要也很简单的pattern:迭代器!
我们可以提供一个统一入口的迭代器,client只需要知道有哪些方法,或是有哪些concrete iterator,并不需要知道他们底层如何实作!现在就让我们来开始吧!

起手式

iterator最主要的东西就是两个:hasnext、next。要让client知道是否还有下一个,和切换到下一个!

定义interface

interface iteratorinterface {
  index: number
  datastorage: any
  hasnext(): boolean
  next(): any
  additem(item: any): void
}

实作介面

下面的范例我将会使用map、array这两个常见的介面实作。

class iterator1 implements iteratorinterface {
  index: number
  datastorage: any[]
  constructor() {
    this.index = 0
    this.datastorage = []
  }
  hasnext(): boolean {
    return this.datastorage.length > this.index
  }
  next(): any {
    return this.datastorage[this.index ++]
  }
  additem(item: any): void {
    this.datastorage.push(item)
  }
}
// map
class iterator2 implements iteratorinterface {
  index: number
  datastorage: map<number, any>
  constructor() {
    this.index = 0
    this.datastorage = new map<number, any>()
  }
  hasnext(): boolean {
    return this.datastorage.get(this.index) != undefined
  }
  next(): any {
    return this.datastorage.get(this.index ++)
  }
  additem(item: any): void {
    this.datastorage.set(this.datastorage.size, item)
  }
}

client

我没有实作一个client,所以我是直接new一个类别出来直接使用!

const i = new iterator1()
i.additem(123)
i.additem(456)
i.additem('dolphin')
while(i.hasnext()){
  console.log(i.next())
}
console.log(`====================`)
const i2 = new iterator2()
i2.additem(123)
i2.additem(456)
i2.additem('dolphin')
while(i2.hasnext()){
  console.log(i2.next())
}

结论

会发现iterator 1号 2号的结果都是一样的!他们都只需要让client知道有hasnext、next就好,底层的实作不需要让他们知道!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网