/ Gists / Singleton
On gists

Singleton

JS Patterns

Singleton1.js Raw #

class Singleton {
  static instance = null;

  constructor() {
    if (Singleton.instance) {
      throw new Error("Singleton instance already exists. Use getInstance() method to access it.");
    }
    // Inicializace Singletonu zde
  }

  static getInstance() {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }

  someMethod() {
    console.log("Metoda Singletonu");
  }
}

// Použití Singletonu
const singletonInstance1 = Singleton.getInstance();
const singletonInstance2 = Singleton.getInstance(); // Tady bude vyvolána chyba

console.log(singletonInstance1 === singletonInstance2); // Vrátí true, protože se jedná o stejnou instanci
singletonInstance1.someMethod(); // Vypíše "Metoda Singletonu"

Singleton2.js Raw #

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) 



Singleton3.js Raw #

class Config {
    constructor() {}
    start(){ console.log('App has started') }  
    update(){ console.log('App has updated') }
}
  
const instance = new Config()
Object.freeze(instance)