设计模式

// 单例模式,简单来说就是一个实例只生产一次
// 对于频繁使用且可重复使用的对象,可以极大来减少内存消耗和没必要的垃圾回收。
class SingleObject {
  constructor() {
    // 防止调用new初始化
    if (new.target !== undefined) {
      const errorMsg = "This is single object,Can't use keyword new!";
      const tipMsg = "You should use method getInstance to get instance。";
      throw new Error(`
${errorMsg}
${tipMsg}`)
    }
  }

  static getInstance() {
    // 生产单例
    if (SingleObject.instance) {
      return SingleObject.instance;
    }
    SingleObject.instance = {};
    SingleObject.instance.__proto__ = SingleObject.prototype;
    return SingleObject.instance;
  }

  showMessage() {
    console.log("Hello World!");
  }
}

let instance = SingleObject.getInstance();
instance.showMessage();
instance = SingleObject.getInstance();
instance.showMessage();
/**
 * output:
 * Hello World!
 * Hello World!
 */
原文地址:https://www.cnblogs.com/ronle/p/13559210.html