Singleton Pattern — Design Patterns

A Singleton makes sure a class has only one instance (an object made from that class), and provides global access to that instance: any file can get it. The…

Two parcels in the Kancil Courier warehouse both carry number KCL-0001. The cause: two parts of the app each made their own tracking-number counter, and both started from zero. It's like a bank that puts two queue-ticket machines in its hall, and both start at 001: two customers hold number 001 and get called at the same time.

The Singleton pattern makes sure a class has only one instance, which means one object made from that class. The pattern also provides one global access point: a way to get that instance from any file. So every part of the app uses the same object, like one queue machine for every customer of the bank: the numbers run in order and none repeat. In code, the queue machine is the tracking counter object, and the queue number is the tracking number.

The problem: two counters, two KCL-0001

Kancil Courier has two ways in for parcels: the cashier in the office and the app on the phone. Each one makes its own tracking-number counter from the class TrackingCounter:

class TrackingCounter {
  constructor() {
    this.count = 0
  }

  next() {
    this.count = this.count + 1
    return "KCL-" + String(this.count).padStart(4, "0")
  }
}

const cashierCounter = new TrackingCounter() // in cashier.js
const appCounter = new TrackingCounter()     // in app.js

console.log(cashierCounter.next()) // KCL-0001
console.log(appCounter.next())     // KCL-0001 again!

Every new makes a new object with its own count starting at 0, like two queue machines that both print number 001. But there must be exactly one tracking-number counter.

The class version: getInstance

The class version keeps its instance in the class itself, and provides getInstance() to get it:

class TrackingCounter {
  static instance = null // belongs to the class, not to each object

  static getInstance() {
    if (!TrackingCounter.instance) {
      TrackingCounter.instance = new TrackingCounter() // made once, the first time it's asked for
    }
    return TrackingCounter.instance
  }

  constructor() {
    this.count = 0
  }

  next() {
    this.count = this.count + 1
    return "KCL-" + String(this.count).padStart(4, "0")
  }
}

const a = TrackingCounter.getInstance() // in cashier.js
const b = TrackingCounter.getInstance() // in app.js

console.log(a === b)  // true
console.log(a.next()) // KCL-0001
console.log(b.next()) // KCL-0002

In JavaScript: a module is enough

An ES module runs once, and every file that imports it gets the same object. So an object exported from a module is already a singleton, with no class and no getInstance:

// trackingCounter.js
let count = 0

export const trackingCounter = {
  next() {
    count = count + 1
    return "KCL-" + String(count).padStart(4, "0")
  },
}

// cashier.js and app.js both write:
import { trackingCounter } from "./trackingCounter.js"

If the cashier calls trackingCounter.next() first, the cashier gets KCL-0001, then the app gets KCL-0002. trackingCounter can't be newed either, because it is a plain object, not a class. In many JavaScript projects, this is how a singleton is written.

The cost: hidden global state

One shared object also means one shared state, tests included. In this code, the function test prints pass or fail for one test, and both tests expect KCL-0001:

function test(name, fn) {
  try {
    fn()
    console.log("pass: " + name)
  } catch (e) {
    console.log("fail: " + name + ", " + e.message)
  }
}

test("issue the first number", () => {
  const r = trackingCounter.next()
  if (r !== "KCL-0001") throw new Error("got " + r)
})

test("today's first number is KCL-0001", () => {
  const r = trackingCounter.next()
  if (r !== "KCL-0001") throw new Error("got " + r)
})
// pass: issue the first number
// fail: today's first number is KCL-0001, got KCL-0002

The second test fails, even though its code is exactly the same as the first. The reason: count is already 1, left over from the test before. Run alone, the second test passes. Run together with the first test, it fails. So the result of a test depends on the order of the tests, and the cause is hard to find.

The same problem appears when debugging (looking for the cause of a bug). Code in any file can change the state of trackingCounter, and a function that uses trackingCounter inside doesn't show that in its parameters. There are two fixes. First, pass the counter in as a parameter (function createParcel(counter, kg)), so each test can make a fresh counter. Second, provide a way to reset the counter before each test. The Dependency Injection lesson explains the first fix in more detail later.

When to use it, when not to

⚠️ The second instance that quietly appears

TL;DR: A Singleton makes sure a class has only one instance (an object made from that class), and provides global access to that instance: any file can get it. The class version uses static instance (a property of the class itself) and getInstance(): the object is made once, then every call returns the same object (if a and b are two results, a === b is true). In JavaScript, an object exported from an ES module is already a singleton, because a module runs once. Its main weakness: hidden global state (shared data that can be changed from anywhere), which makes testing and debugging harder. For example, two identical tests expect KCL-0001, and the second test gets KCL-0002. Use a Singleton only for what has to be one (the tracking counter, config, a logger), and never for per-user data on a server.

⚡ Two news, two KCL-0001s

Write:

const cashierCounter = new TrackingCounter() // in cashier.js
const appCounter = new TrackingCounter()     // in app.js
Guess first: TrackingCounter is a class for tracking-number counters. Its count starts at 0, and every next() adds 1 and returns a number like KCL-0001. The cashier, then the app, each call next() once on their own counter. What numbers come out?

KCL-0001 both times. Every new makes a new object with its own count starting at 0.

Meaning: Two news make two instances (objects of the class TrackingCounter), like a bank with two queue-ticket machines that both start at 001. A Singleton prevents this: a class has only one instance, with one global access point (a way to get it from any file).

⚡ getInstance makes it once

Write:

class TrackingCounter {
  static instance = null // belongs to the class, not to each object

  static getInstance() {
    if (!TrackingCounter.instance) {
      TrackingCounter.instance = new TrackingCounter() // made once, the first time it's asked for
    }
    return TrackingCounter.instance
  }
}

Meaning: static instance is kept in the class, not in each object. The first call to getInstance() makes the object. Every later call returns the object that already exists, so two results of TrackingCounter.getInstance(), say a and b, are the same object: a === b is true. In JavaScript, an object exported from an ES module is already a singleton, because a module runs once.

⚡ The cost: state that carries over

Guess first: trackingCounter is one tracking counter that every file shares (a singleton). Two tests with exactly the same code call trackingCounter.next() and expect KCL-0001. Do both pass?

No. The second test gets KCL-0002, because the first test already raised the count. Run alone, the second test passes.

Meaning: One shared object means one shared state (data that is kept and can change). Reset the counter before each test, or pass the counter as a parameter to the function that uses it. Use a Singleton only for what has to be one, never for per-user data on a server.

What you will learn