目前遵循单一职责的原则, 单例的管理函数和单例的创建函数是分开的, 如下:function handleSingleton (createFn){ // createFn是单例的创建函数(例如创建一个div元素等)
let created = null
return function (...rest) { return created || (created = createFn.apply(this, rest))
}
}但这样有个问题: 单例创建后无法有效地销毁. 为了解决这个问题, 增加了一个destroyFn函数用于销毁闭包内的created变量, 并根据传入的type来决定是调用createFn来创建单例, 还是调用destroyFn来销毁单例:function handleSingleton (createFn, destroyFn){ let created = null
// 判断传入的type
return function (type, ...rest) { if (type === 'create') { return created || (created = createFn.apply(this, rest))
} else if (type === 'destroy') {
destroyFn.call(this, created, ...rest)
created = null
} else { throw new Error('\'type\' can either be \'create\' or \'destroy!\'')
}
}
}有没有更好的办法呢?
1 回答
慕码人2483693
TA贡献1860条经验 获得超9个赞
在handleSingleton的返回函数上添加一个销毁函数,用于销毁自己
function handleSingleton (createFn){ // createFn是单例的创建函数(例如创建一个div元素等) let created = null let ret = function (...rest) { return created || (created = createFn.apply(this, rest)) } ret.distroy = function(distroyFn){ distroyFn && distroyFn() created = null } return ret }
添加回答
举报
0/150
提交
取消