• javascript设计模式——Singleton


    单例模式指的是只能被实例化一次。

    推荐阅读:

    http://blog.mgechev.com/2014/04/16/singleton-in-javascript/

    比较通用的一种Singleton模式

    var mySingleton = (function () {
      // Instance stores a reference to the Singleton
      var instance;
      function init() {
        // Singleton
        // Private methods and variables
        function privateMethod(){
            console.log( "I am private" );
        }
        var privateVariable = "Im also private";
        var privateRandomNumber = Math.random();
        return {
          // Public methods and variables
          publicMethod: function () {
            console.log( "The public can see me!" );
          },
          publicProperty: "I am also public",
          getRandomNumber: function() {
            return privateRandomNumber;
          }
        };
      };
      return {
        // Get the Singleton instance if one exists
        // or create one if it doesn't
        getInstance: function () {
          if ( !instance ) {
            instance = init();
          }
          return instance;
        }
      };
    })();
    var singleA = mySingleton.getInstance();
    var singleB = mySingleton.getInstance();
    console.log( singleA === singleB); // true

     这种写法的好处有

    1.只能实例化一次

    2.可以存在私有函数

    3.变量不可访问,不容易被修改。

  • 相关阅读:
    多态
    封装
    继承
    面向对象
    2.机器学习相关数学基础
    作业1 机器学习概述
    作业15 语法制导的语义翻译
    作业14 算符优先分析
    作业13 自下而上语法分析
    作业12 实验二 递归下降语法分析
  • 原文地址:https://www.cnblogs.com/winderby/p/4318441.html
Copyright © 2020-2023  润新知