Huauauaa / cheat-sheet

https://huauauaa.github.io/cheat-sheet/
0 stars 0 forks source link

设计模式 #32

Open Huauauaa opened 2 years ago

Huauauaa commented 2 years ago

单例

class Singleton {
  constructor(name) {
    this.name = name;
    this.instance = null;
  }

  static getInstance(name) {
    if (!this.instance) {
      this.instance = new Singleton(name);
    }
    return this.instance;
  }
}

es5

var Singleton = function (name) {
  this.name = name;
  this.instance = null;
};

Singleton.getInstance = function (name) {
  if (!this.instance) {
    this.instance = new Singleton(name);
  }
  return this.instance;
};