外观
迭代器模式
迭代器模式是提供一种方法顺序访问聚合对象中的各个元素。
迭代器模式一种相对简单的模式,简单到有时候都忘了它是一种设计模式,目前绝大部分语言都内置了迭代器。
内部迭代器
外界不用关心迭代器内部的实现。
js
function forEach(arr, callback, context) {
for (let i = 0; i < arr.length; i++) {
callback.call(context || this, arr[i], i, arr)
}
}
forEach([1, 2, 3], function (v, i, arr) {
console.log(v, i, arr)
})外部迭代器
必须显式地请求迭代下一个元素,这增加了调用的复杂度,但提高了灵活性,可手动控制迭代过程。
js
function iterator(obj) {
let current = 0
const next = function () {
current++
}
const isDone = function () {
return current >= obj.length
}
const getCurItem = function () {
return obj[current]
}
return {
next,
isDone,
getCurItem
}
}
// 手动迭代
const it = iterator([1, 2, 3])
while (!it.isDone()) {
console.log(it.getCurItem())
it.next()
}迭代器应用
按优先级使用不同的文件上传组件对象,在获取上传对象的函数中,若获取不到上传对象则返回 false。可用迭代器模式按优先级去循环获取上传对象。
js
const getActiveUploadObj = function () {}
const getFlashUploadObj = function () {}
const getHtml5UploadObj = function () {}
const iteratorUploadObj = function (...args) {
for (let i = 0; i < args.length; i++) {
const uploadFn = args[i]
const uploadObj = uploadFn()
if (uploadObj !== false) {
return uploadObj
}
}
}
const uploadObj = iteratorUploadObj(
getActiveUploadObj,
getFlashUploadObj,
getHtml5UploadObj
)