Skip to content

单例模式

定义

保证类仅有一个实例,并提供一个全局访问点。

惰性单例

实例

惰性单例指的是在需要的时候才创建对象实例。

js
const SingleDog = (function () {
  let instance;
  return function Dog(name) {
    return instance || (instance = this);
  };
})();

const dog1 = new SingleDog();
const dog2 = new SingleDog();

console.log(dog1, dog2, dog1 === dog2);

Released under the MIT License.