JavaScript 中第一个重要的设计模式,即保证一个类有且仅有一个实例对象,单例模式在日常的开发中使用的非常频繁,比如

  1. 全局挂载对象
  2. 在其他设计模式中使用

全局挂载对象会造成污染全局变量,在前端工程化的当下,不建议直接在window对象下挂载

函数方式构建单例模式

/** 函数版 
 *  借助闭包 获取 单例
 */
let singleFunction = (function(){
    let single = undefined; 
    return function(fun){
        if(fun instanceof Function){
            if(single===undefined){
                single = [fun]
            }else{
                single = [...single,fun]
            }
        }
        return single;
    }
})()

let a = singleFunction(()=>{console.log('我是a设置的方法')});
let b = singleFunction();
console.log(a===b); //true
b.forEach((ele)=>{
    ele()  //我是a设置的方法
})

class版

class Single {
    static single;
    fun = []; // 对外事件
    constructor(){
        if(!Single.single){
            Single.single = this
        }
        return Single.single
    }
    getFun(){
        this.fun.forEach(element => {
            element();
        });
    }
    setFun(fun){
        this.fun.push(fun);
    }
}
let c = new Single();
let d = new Single();
console.log(c===d); // true

d.setFun(()=>{console.log('我是d设置的方法')})
c.getFun() //我是d设置的方法

With great power there must come great responsibility.