迭代子模式:定义this
迭代子模式,又称游标模式,是一种用于对汇集进行顺序访问规则的模式,是一种行为模式;它用于提供对汇集对象的一种统一的访问接口,使客户可以在不了解汇集对象内部结构的状况对汇集对象进行访问。它涉及两个部分,一个是汇集对象,一个迭代子对象,迭代对象(Iterator)用于提供访问汇集对象的标题访问方法;spa
主要组成角色:prototype
基础代码:code
//抽象汇集对象类 public Collections() { this.arrs = ['xx']; this.iterator = function() { console.log('须要返回一个Iterator对象'); return null; }; this.size = function() { //Iterator 须要引用 this.arrs.length; } this.get = function(idx) { //Iterator 须要引用 return this.arrs[idx]; } }; //迭代对象 public Iterator (colls) { this.colls = colls; this.index = 0; this.next = function() { if > this.colls.size() //引用 this.index ++ ; } this.prev = function() { //if < 0 this.index--; } this.get = function() { this.colls.get(this.index); //引用 } //more }
迭代子模式结构图 对象
实例blog
1. 抽象迭代角色接口
function abstractIterator() { this.prev = functiojn() { }; this.next = function() { }; this.first = function() { }; this.hasNext = function() { }; this.get = function() { }; }
2. 具体迭代角色get
function Iterator(colls) { this.colls = colls; this.index = 0; }; Inteator.prototype = abstractIterator.prototype; Inteator.prototype.prev = function() { if (this.index > 0) this.index --; }; Inteator.prototype.next = function() { if (this.index < this.colls.size()) { this.index++; } }; Inteator.prototype.first = function() { this.index = 0; }; Inteator.prototype.hasNext = function() { return this.index < this.colls.size(); }; Inteator.prototype.get = function() { return this.colls.get(this.index); };
3. 抽象汇集角色it
function abstractCollection() { this.iterator = function() { return null; }; }
4. 具体实现汇集角色公共方法io
function Collection() { this.arrars = ['XXX', 'yyy', 'ZZZ']; }; Collection.prototype = abstractCollection.prototype; Collection.prototype.iterator = function() { return new Iterator(this); }; Collection.prototype.size = function() { return this.arrays.length; }; Collection.prototype.get = function(index) { return this.arrays[index]; };
5. 客户端使用
function Client() { var colls = new Collection(); var iterator = colls.iterator(); for (iterator.hasNext()) { console.log(iterator.get()); iterator.next(); } };
其余说明
把聚象对象的访问逻辑统一到迭代对象里,让客户能够不用了解聚象对象的结构,就能够一种统一的方式访问,汇集与业务逻辑的解耦!