JavaScript中的单例设计模式

lxf2023-04-21 12:10:02

单例设计模式是一种程序设计模式,它能够确保某一类只有一个案例,同时提供一个全局性访问点来浏览该案例,我们可以用单例设计模式来处理全局状态和共享。

在JavaScript中,单例设计模式能通过多种形式完成,以下属于一些常见的控制方式

  1. 对象字面量

应用对象字面量能够轻松地建立单例对象,比如:

const singleton = {
  property1: "value1",
  property2: "value2",
  method1: function () {
    // ...
  },
  method2: function () {
    // ...
  },
};

所述编码中,采用了一个对象字面量来建立单例对象,该目标包括了一些属性和方法。因为JavaScript中对象字面量本来就是单例模式的,因而不需要额外代码来确保单例模式。

  1. 对象

在JavaScript中,每一个对象都能够用以建立单例对象,比如:

function Singleton() {
  // 判断是否案例
  if (typeof Singleton.instance === "object") {
    return Singleton.instance;
  }

  // 复位单例对象
  this.property1 = "value1";
  this.property2 = "value2";
  Singleton.instance = this;
}

const instance1 = new Singleton();
const instance2 = new Singleton();

console.log(instance1 === instance2); // 导出 true

所述编码中,采用了一个对象来建立单例对象。在构造方法中,最先判断是否单例模式案例,如果出现则直接回到该案例,不然建立单例对象并把它储存在 Singleton.instance 特性中。因为JavaScript中每一个对象本身就是一个单例模式,因而不需要额外代码来确保单例模式。

  1. 控制模块方式

应用控制模块方式能够创建一个仅有单独案例的对象,比如:

const Singleton = (function () {
  let instance;

  function init() {
    // 建立单例对象
    const object = new Object("I am the instance");
    return object;
  }

  return {
    getInstance: function () {
      if (!instance) {
        instance = init();
      }
      return instance;
    },
  };
})();

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

console.log(instance1 === instance2); // 导出 true

所述编码中,采用了一个马上执行函数来建立单例对象。在这个函数中,重新定义了一个私有变量 instance 用以存放单例模式案例,而 init 函数公式乃是用以建立单例模式案例的办法。最终,回到一个对象,该目标包括一个 getInstance 方式,此方法用以获得单例模式案例。

通过以上方法达到的单例设计模式,能够确保在程序执行期内,某一类只有一个案例,且该案例能够在任何时候浏览。