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)

}

}

// 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就好,底层的实作不需要让他们知道!

以上就是本文的全部内容,希望对大家的学习有所帮助。

 

标签

发表评论