Singleton Pattern

The conventional singleton pattern is really something that is used to overcome the fact that all code must be in a class.

  1. class Singleton {
  2. private static instance: Singleton;
  3. private constructor() {
  4. // do something construct...
  5. }
  6. static getInstance() {
  7. if (!Singleton.instance) {
  8. Singleton.instance = new Singleton();
  9. // ... any one time initialization goes here ...
  10. }
  11. return Singleton.instance;
  12. }
  13. someMethod() { }
  14. }
  15. let something = new Singleton() // Error: constructor of 'Singleton' is private.
  16. let instance = Singleton.getInstance() // do something with the instance...

However if you don’t want lazy initialization you can instead just use a namespace:

  1. namespace Singleton {
  2. // ... any one time initialization goes here ...
  3. export function someMethod() { }
  4. }
  5. // Usage
  6. Singleton.someMethod();

Warning : Singleton is just a fancy name for global

For most projects namespace can additionally be replaced by a module.

  1. // someFile.ts
  2. // ... any one time initialization goes here ...
  3. export function someMethod() { }
  4. // Usage
  5. import {someMethod} from "./someFile";