Skip to content

Decide on and document a convention for singletons

username-removed-408230 requested to merge google-singletons-are into master

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

The simplest implementation uses an object literal to contain the logic.

gl.MyThing = {
  prop1: 'hello',
  method1: () => {}
};

A live example of this is GfmAutoComplete

Another approach makes use of ES6 class syntax.

let singleton;

class MyThing {
  constructor() {
    if (!singleton) {
       singleton = this;
       singleton.init();
     }
      return singleton;
  }

  init() {
    this.prop1 = 'hello';
  }

  method1() {}
}

gl.MyThing = MyThing;

A live example of this is Sidebar

Another functional approach to define Singleton using Javascript Revealing Module Pattern is like below

/**
  *  1. It instantiates only a single object
  *  2. It is safe – it keeps the reference to the singleton inside a variable, which lives inside a lexical closure, so it is not accessible by the outside world
  *  3. It allows privacy – you can define all private methods of your singleton inside the lexical closure of the first module pattern
  *  4. No this keyword trap (no wrong context referring)
  *  5. No use of new keyword
  *  6. Easy to write test code
  */
//
const Singleton = (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;
    }
  };
})();

const singletonObj = Singleton.getInstance()

Are there points in the code the reviewer needs to double check?

What does this MR do?

Creates a space for discussion and contribution for interested devs.

Why was this MR needed?

Screenshots (if relevant)

Does this MR meet the acceptance criteria?

What are the relevant issue numbers?

Merge request reports