Web Dev Notes

AboutContact

Singleton Pattern

Singletons are classes which can be instantiated once, and can be accessed globally. This single instance can be shared throughout our application, which makes Singletons great for managing global state in an application.

(Dis) advantages

Singletons are actually considered an anti-pattern, and can be avoided in JavaScript.

Source : Patterns.dev

Using an object literal

const Config = {
  start: () => console.log("App has started"),
  update: () => console.log("App has updated"),
};

// We freeze the object to prevent new properties being added and existing properties being modified or removed
Object.freeze(Config);

Config.start(); // "App has started"
Config.update(); // "App has updated"

Config.name = "Robert"; // We try to add a new key
console.log(Config); // And verify it doesn't work: { start: [Function: start], update: [Function: update] }

Using classes

class Config {
  constructor() {}
  start() {
    console.log("App has started");
  }
  update() {
    console.log("App has updated");
  }
}

const instance = new Config();
Object.freeze(instance);

Singleton Pattern

Singletons are classes which can be instantiated once, and can be accessed globally. This single instance can be shared throughout our application, which makes Singletons great for managing global state in an application.

(Dis) advantages

Singletons are actually considered an anti-pattern, and can be avoided in JavaScript.

Source : Patterns.dev

Using an object literal

const Config = {
  start: () => console.log("App has started"),
  update: () => console.log("App has updated"),
};

// We freeze the object to prevent new properties being added and existing properties being modified or removed
Object.freeze(Config);

Config.start(); // "App has started"
Config.update(); // "App has updated"

Config.name = "Robert"; // We try to add a new key
console.log(Config); // And verify it doesn't work: { start: [Function: start], update: [Function: update] }

Using classes

class Config {
  constructor() {}
  start() {
    console.log("App has started");
  }
  update() {
    console.log("App has updated");
  }
}

const instance = new Config();
Object.freeze(instance);