ruk·si

🍦 JavaScript Pattern
Singleton

Updated at 2015-05-13 16:07

Singleton pattern allow creating only one instance of a prototype.

var Universe = (function() {
  'use strict';

  var instance = null;

  /**
   * @constructor
   */
  var Universe = function() {
    if (instance !== null) {
      return instance;
    }
    // All the initialization here.
    this.startTime = 0;
    instance = this;
  };

  Universe.getInstance = function() {
    return new Universe();
  };
  Universe.prototype.getTime = function() {
    return this.startTime;
  };
  Universe.prototype.tick = function() {
    return ++this.startTime;
  };

  return Universe;
}());

// Two different ways of accessing the singleton,
// choose which one you like.
var uni1 = new Universe();
var uni2 = new Universe();
var uni3 = Universe.getInstance();
console.assert(uni1 === uni2);
console.assert(uni2 === uni3);
console.assert(uni1.getTime() === 0);
console.assert(uni3.getTime() === 0);
console.assert(uni2.tick() === 1);
console.assert(uni1.getTime() === 1);
console.assert(uni3.tick() === 2);
var uni4 = Universe.getInstance();
console.assert(uni4.getTime() === 2);

var NotSingleton = function() {};
var not1 = new NotSingleton();
var not2 = new NotSingleton();
console.assert(not1 !== not2);