DevPath · Learn to code ESPTEN

Design patterns

Singleton and observer

Singleton pattern

It guarantees that there is a single instance of an object throughout the application, with a global access point. Useful for configuration, caches or connections.

const Settings = (function () {
  let instance;

  function create() {
    return { theme: "light", language: "en" };
  }

  return {
    get() {
      if (!instance) instance = create();
      return instance;
    },
  };
})();

const a = Settings.get();
const b = Settings.get();
console.log(a === b); // true: it is the same instance

Observer pattern

It defines a one-to-many relationship: a subject keeps a list of observers and notifies them when a change happens. It is the foundation of event systems.

class Subject {
  constructor() {
    this.observers = [];
  }
  subscribe(fn) {
    this.observers.push(fn);
  }
  notify(data) {
    for (const obs of this.observers) obs(data);
  }
}

const news = new Subject();
news.subscribe((headline) => console.log("Reader 1:", headline));
news.subscribe((headline) => console.log("Reader 2:", headline));
news.notify("New version of JavaScript!");

Examples

Observer: reactive task list

class Emitter {
  constructor() { this.subs = []; }
  on(fn) { this.subs.push(fn); }
  emit(data) { this.subs.forEach((fn) => fn(data)); }
}
const e = new Emitter();
e.on((x) => console.log("Received:", x));
e.emit("hello");
e.emit("world");
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Module and factory patternsStrategy pattern →