在设计模式中,有一种特别的模式,叫单例模式,单例模式是指:通过调用同一个方法生成的对象永远只有一个(多次调用生成的对象是相同)。下面是实现的一个存储数据的单例对象的栗子。
// 实现一个单例模式模式的storage
function Storage(){
}
// 使用闭包一个_instence对象,由于闭包的作用,这个对象一旦实例化,就会一直存在内存中
Storage.getInstence = (function(){
var _instence = null
return function(){
if(!_instence){
_instence = new Storage()
}
return _instence
}
})()
Storage.prototype.setItem = function(key,value){
this[key] = value
}
Storage.prototype.getItem = function(key,value){
return this[key]
}
// 即使多次创建对象也是同样的
var storage = Storage.getInstence()
storage.setItem("name","duanlin")
console.log(storage.getItem("name"))
var state = Storage.getInstence()
console.log(storage === state)//true