js单例模式

2019-10-14  本文已影响0人  GGatsby

1.使用闭包
2.闭包中判断实例是否已存在,若存在直接返回,否则new新实例

function Constructor(){}

// 单例模式
Constructor.getInstance = function() {
  let instance = null;

  return function(){
    if(instance == null) {
      instance = new Constructor();
    }

    return instance;
  }
}

应用场景:
只需要生成一个唯一对象的时候,需要用到单例模式。
如登录框,windows任务管理器,回收站,日志文件(常见场景),线程池等。

上一篇 下一篇

猜你喜欢

热点阅读