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.变量不可访问,不容易被修改。

你可能感兴趣的:(JavaScript)