JS-Javascript 迭代器设计模式 Iterator pattern

来源:互联网 发布:神户大学 知乎 编辑:程序博客网 时间:2024/06/01 09:34

这篇博文简短的提一下Iterator的设计模式,以及这种设计模式给我们带来什么样的好处。

1.begin

为了体现面向对象的特性(近年来的ES6为这方面做了很大的努力),此篇博文的语言编写基于typescript,当然也会附上原生js的书写方式。

1.1迭代器给我们带来了什么样的好处

迭代器可以使我们快速的遍历一个序列对象,一个良好的迭代器使我们不用了解该序列底层的结构,而只用关心拿到值之后的处理,并且迭代器是相当轻量的,对于创建一个迭代器,它的代码开销是非常小的。

1.2自己实现一个简单的js迭代器

在这里我们称为iterator设计模式,该设计模式就是为了创建一个简单的迭代器,当然时间有限,这里创建出来的迭代器以传入数组为基础进行迭代。

Typescript

interface MyIteratorInterface<T>{    hasNext():boolean,    next():T}class MyIterator<T> implements MyIteratorInterface<T>{    //数组指针    pointer:number = 0;    //步长    step:number;    //数组对象    arr:Array<T>;    constructor(arr:Array<T>,step?:number){        this.arr = arr;        this.step = step || 1;    }    hasNext(){        if(this.arr[this.pointer + this.step]){            return true;        }        return false;    }    next(){        while(this.pointer <= this.arr.length){            if(this.pointer++ % this.step == 0){                return this.arr[this.pointer - 1];            }        }    }}let arr:number[] = [1,1,23,2,42,3,52,3,72,3];let myIterator:MyIterator<number> = new MyIterator<number>(arr,3);console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);console.log(`next is ${myIterator.next()} and hasNext is ${myIterator.hasNext()}`);

运行结果如下:
这里写图片描述

Javascript

//迭代器对象let Iterator = function(arr,step){    if(!arr || !step){        throw new Error("arr and step is necessary");    }    //需要迭代的对象    this.arr = arr;    //当前迭代的指针    this.cursor = 0;    //迭代的步长    this.step = step;}Iterator.prototype = {    //获得下一个元素    next:function(){        while(this.cursor < this.arr.length){            if(this.cursor++ % this.step == 0){                return this.arr[this.cursor - 1];            }        }    },    //是否还有下一个元素    hasNext:function(){        let tempCursor = this.cursor;        while(tempCursor < this.arr.length){            if(tempCursor++ % this.step == 0){                return true;            }        }        return false;    }};let it = new Iterator([1,2,42,3,52,3,2,4],2);console.log(it.next(),it.hasNext());console.log(it.next(),it.hasNext());console.log(it.next(),it.hasNext());
原创粉丝点击