zoukankan      html  css  js  c++  java
  • 设计模式

    // 单例模式,简单来说就是一个实例只生产一次
    // 对于频繁使用且可重复使用的对象,可以极大来减少内存消耗和没必要的垃圾回收。
    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!
     */
  • 相关阅读:
    [NOI2003][bzoj1507] 文本编辑器 editor [splay]
    GDKOI 游记
    [填坑完毕] 寒假作业计划
    省选算法学习-数据结构-splay
    NOIP2017游记
    真·总结
    赛前
    十一黄(xun)金(lian)周感想
    9.17 模拟赛
    9.14 模拟赛
  • 原文地址:https://www.cnblogs.com/ronle/p/13559210.html
Copyright © 2011-2022 走看看