设计模式-javascript实现【单例模式】

定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

1. 用传统类的方式实现单例模式

  • Singleton 提供访问单例对象的统一接口:getInstance()
class Singleton {
  constructor(){
    this.instance = null;
  }
  
  static getInstance (){
    if(!this.instance){
      this.instance = new Singleton();
    }
    return this.instance;
  }
}

const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2);
  • Singleton 使用new 关键字实现单例模式
class Singleton {
  constructor(){
    if(Singleton.instance) return Singleton.instance;
    Singleton.instance = this;
  }
}

const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2);

2. 使用构造函数实现单例模式

function Singleton(name) {
  this.name = name;
}

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

const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2);

3. 通用的惰性单例模式

将创建对象的逻辑和管理单例的逻辑分开,通用的单例模式只负责管理单例,而创建对象的逻辑通过
参数传递进来。

// 管理单例
function getSingle(fn) {
  let result;
  return function(...args){
    return result || (result = fn.apply(this, args));
  }
}

// 创建对象
const createObj = function() {
  return { name: 'jack' };
}
const singleCreate = getSingle(createObj);
const obj1 = singleCreate();
const obj2 = singleCreate();
console.log(obj1 === obj2);
posted @ 2021-11-20 01:09  箫笛  阅读(99)  评论(0)    收藏  举报