JavaScript singleton pattern

In JavaScript,  it would let you feel struggle to implement singleton design pattern. This is my first experiment:
     
View = {
       
        _viewer: undefined,

        initView: function() {
          // init view
        },

        getView: function() {
          // get view
          return _viewer;
        }

     };
But I figure out this approach can't express 'encapsulate', so the user can get _viewer directly. Therefore, I decide to rewrite it. I rewrite it to:
     
var View = ( function() {
       
        var _viewer = undefined;

        function init() {
          // init view
        };

        function getView() {
          // get view
          return _viewer;
        };
  
        return {
           init(): { init(); },
           getView(): { return getView(); }
        };

     };
} ) ();
This method can achieve 'encapsulate', uses its method like View.getView(), but you have to program the interface two times on function and return parts. Finally, I decide to use the bottom method, this method is the perfect solution for me now.
// unstrict mode:
var View = ( function() {
       
        if ( arguments.callee._singletonInstance )
           return arguments.callee._singletonInstance;
        arguments.callee._singletonInstance = this;

        var _viewer = undefined;

        this.init = function() {
          // init view
        };

        this.getView = function() {
          // get view
          return _viewer;
        };

     };
} ) ();

new View();

// strict mode:     
var View = ( function() {
       
        if (View.prototype._singletonInstance)
           return View.prototype._singletonInstance;

        View.prototype._singletonInstance = this;

        var _viewer = undefined;

        this.init = function() {
          // init view
        };

        this.getView = function() {
          // get view
          return _viewer;
        };

     };
} ) ();

new View();
This method you also can use its method like this way View.getView();, however you needn't multiple define the interfaces.

Reference:
http://stackoverflow.com/questions/1635800/javascript-best-singleton-pattern
http://fstoke.me/blog/?p=1932
http://www.dotblogs.com.tw/blackie1019/archive/2013/08/30/115977.aspx

Comments

Popular posts from this blog

董事長您好

After reading Steve Jobs Autobiography

Drawing textured cube with Vulkan on Android