就让风继续吹吧

贫瘠小行星,种一颗玫瑰

导航

ES6 实现单例模式

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

  • 通过构造函数
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)

 

posted on 2021-04-23 10:11  就让风继续吹吧  阅读(1626)  评论(1编辑  收藏  举报