Skip to content

Files

Latest commit

830bd25 Β· Apr 20, 2019

History

History
33 lines (23 loc) Β· 544 Bytes

singleton.md

File metadata and controls

33 lines (23 loc) Β· 544 Bytes

Singleton Pattern

Singleton creational design pattern restricts the instantiation of a class to a single object.

Implementation

class Singleton {
  constructor() {
    if (!!Singleton.instance) {
      return Singleton.instance;
    }

    Singleton.instance = this;
  }
}

Usage

const i = new Singleton();
const j = new Singleton();

console.log(i); // Singleton {}
console.log(j); // Singleton {}

console.log(i === j); // true

Caveats

  • Singletons represent a global state and may reduces testability.