zoukankan      html  css  js  c++  java
  • 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.变量不可访问,不容易被修改。

  • 相关阅读:
    Linux找回root密码
    关于Linux的随笔笔记
    需求征集系统进度03
    需求征集系统进度02
    需求征集系统进度01
    第六周总结
    阅读笔记03
    第一周总结
    第五周总结
    阅读笔记02
  • 原文地址:https://www.cnblogs.com/winderby/p/4318441.html
Copyright © 2011-2022 走看看