千家信息网

JavaScript设计模型Iterator实例解析是怎样的

发表于:2024-10-18 作者:千家信息网编辑
千家信息网最后更新 2024年10月18日,这期内容当中小编将会给大家带来有关JavaScript设计模型Iterator实例解析是怎样的,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Iterator Pat
千家信息网最后更新 2024年10月18日JavaScript设计模型Iterator实例解析是怎样的

这期内容当中小编将会给大家带来有关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) }}

// mapclass iterator2 implements IteratorInterface { index: number dataStorage: Map constructor() { this.index = 0 this.dataStorage = new Map() } 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就好,底层的实作不需要让他们知道!

上述就是小编为大家分享的JavaScript设计模型Iterator实例解析是怎样的了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。

0