js单例模式的实现

下面介绍js实现单例模式的两种方法:
一、在类里面定义一个静态方法,用来创建类的实例

class Singleton {
  // 定义一个静态方法  不会被修改
  // 通过static定义的方法,只能通过Singleton.getInstance来访问,不能通过new Singleton的实例访问,这样会抛出一个错误
  static getInstance = (function () {
    let instance
    // 通过闭包来存储实例
    return function () {
      if (!instance) {
        instance = new Singleton()
      }
      return instance
    }
  })()
}

const obj1 = Singleton.getInstance()
const obj2 = Singleton.getInstance()
if(obj1 === obj2){
    console.log('是同一个对象')
}else{
    console.log('不是同一个对象')
}

创建对象的时候,不使用new来创建,而是调用getInstance方法来创建对象,这样创建出来的对象,就会是同一个对象。

二、在类的构造方法判断当前类的实例是否存在,存在就返回当前类实例,不存在就创建实例并返回

在constructor中,加上这几行代码

class Singleton {
  constructor(name) {
        this.name = name

        if(!Singleton.instance) {
            Singleton.instance = this
        }
        return Singleton.instance
    }
}

let obj1 = new Singleton("张三");
let obj2 = new Singleton("张三");

if(obj1 === obj2){
    console.log('是同一个对象');
}else{
    console.log('不是同一个对象');
}

这种方法,就可以使用new来创建对象,创建出来的对象也是同一个对象。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: