Skip to content

单例模式

单例模式是确保一个类只有唯一实例的一种方式,并提供全局的 API 来获取这个实例,在 JS 中可以使用构造函数返回值的特性来生成单例模式的类:

js
/**
 * ES6类的方式实现
 */
export class Singleton {
  constructor(name) {
    if (!Singleton.instance) {
      this.name = name
      Singleton.instance = this
    } else {
      return Singleton.instance
    }
  }
}

/**
 * 传统方式实现,利用闭包
 */
export const Singleton2 = (() => {
  let instance

  const createInstance = (name) => {
    return {
      name,
    }
  }

  return {
    getSingleton(name) {
      if (!instance) {
        instance = createInstance(name)
      }
      return instance
    },
  }
})()

Singleton类使用方法和寻常类没有区别,不过只会初始化一次:

js
// 打开控制台可以看到结果
const a = new Singleton('mouse')
const b = new Singleton('cat')

const a2 = Singleton2.getSingleton('mouse')
const b2 = Singleton2.getSingleton('cat')

console.log('1:', a, b, a === b) // true
console.log('2:', a2, b2, a2 === b2) // true

通过 ES6 类的方式来实现会稍好一些,这种方式下单例类和普通类并无太多区别。单例模式还会区分惰性单例还是非惰性单例,就是实例初始化的时机区分,对于实例初始化很耗费资源的情况,惰性模式可以节省一些资源,非惰性实例则可以节省些准备时间,并无优劣区别,看情况使用就好。