单例模式:保证一个类只有一个实例,并且提供它的全局访问点。

  • 通过构造函数
class Singleton {
  constructor() {
    if(!Singleton.instance) {
      // 将 this 挂载到单例上
      Singleton.instance = this
    }
    return Singleton.instance
  } 
}
const a = new Singleton() 
const b = new Singleton()
console.log(a === b)
  • 通过静态方法
class Singleton {
  static instance = null

  static getInstance() {
    if(!Singleton.instance) {
      Singleton.instance = new Singleton()
    }
    return Singleton.instance
  }
}
const a = new Singleton()
const b = new Singleton()
console.log(a === b)
  • 通过代理模式
class Cat {}

const createSingleCat = (() => {
  let instance
  return () => {
    if (!instance) {
      instance = new Cat()
    }
    return instance
  }
})()
const a = new Singleton()
const b = new Singleton()
console.log(a === b)

 

相关文章:

  • 2018-11-13
  • 2019-02-25
  • 2021-07-03
  • 2021-07-07
  • 2021-09-24
  • 2021-08-19
  • 2021-09-23
  • 2021-11-17
猜你喜欢
  • 2021-08-14
  • 2021-07-25
  • 2021-08-26
  • 2021-11-30
  • 2021-10-20
  • 2017-12-21
相关资源
相似解决方案