(7)JavaScript单例模式

2019-04-27  本文已影响0人  jaimor

概述

单例模式,顾名思义就是整个上下文中只存在一个实例。要实现这种模式,需要用到JavaScript闭包、私有变量相关知识。单例模式可以节省内存空间,减小开销。

实现

var Singleton = (function () {
  var _instance = null;  //保存实例
  function F() {};       //功能类
  F.prototype = {
    say: function (msg) {
      console.log(`i want to say: ${msg}`);
    }
  };
  return {
    getInstance: function () {    //获取到单例
      if (!_instance) {
        console.log("new instance");
        return _instance = new F();
      }  
      return _instance;
    }
  }
})();

测试

Singleton.getInstance().say("Hi");
Singleton.getInstance().say("Hi");
Singleton.getInstance().say("Hello");
//输出
// new instance
// i want to say: Hi
// i want to say: Hi
// i want to say: Hello
上一篇 下一篇

猜你喜欢

热点阅读