JavaScript 设计模式核⼼原理与应⽤实践 | 小册免费学

531 阅读1分钟
单例模式

单例模式代码模板

/**
* 单例模板 class的方式
*/
class Sing{
    static getInstance(){
        if(!Sing.instance)
            Sing.instance=new Sing();
        }
     return Sing.instance;
    }

}
/**
构造函数 --通过闭包保存实例对象
*/
Sing.getInstance=(function(){
  let instance=null;
  return function(){
    if(!instance){
        instance=new Sing();
    }
      return instance;
  }
})()
实例:

1. 实现一个 Storage

功能描述: 实现Storage,使得该对象为单例,基于 localStorage 进行封装。实现方法 setItem(key,value) 和 getItem(key)。

class Storage{
    static getInstance(){
        if(!Storage.instance){
          Storage.instance=new Storage();
        }
        return Storage.instance;
    }
    setItem(key,value){
       return window.localStorage.setItem(key,value);
    }
    getItem(key){
      return window.localStorage.getItem(key);
    }
}
function StorageBase(){
}
StorageBase.prototype.getItem=function(key){
    return window.localStorage.getItem(key);
}
StorageBase.prototype.setItem=function(key,value){
     return window.localStorage.setItem(key,value);
}

Storage.getInstance=(function(){
let instance=null;
return function(){
    if(!instance){
        instance=new StorageBase();
    }
    return instance;
}
})()

跟着敲了一遍,单例的模板记住了。