Typescript Design Patterns: Singleton

The Mythical Engineer


singleton-design-pattern

Notes on Singleton Design Pattern

Intent

Ensure a class only has one instance, and provide a global point of access to it.

Applicability

Object Oriented Programming

class Singleton {
  private static instance: Singleton;
  private data: number;

  private constructor() {
    this.data = Math.random();
  }

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

  public getData(): number {
    return this.data;
  }
}

const instance1 = Singleton.getInstance();
console.log(instance1.getData()); // 0.16152774745058918

const instance2 = Singleton.getInstance();
console.log(instance2.getData()); // 0.16152774745058918

console.log(instance1 === instance2); // true

Functional programming

type Singleton = {
  data: number;
};
type ReturnSingleton = () => Singleton

const createSingleton: ReturnSingleton = (() => {
  let instance: Singleton;
  return () => {
    if (!instance) {
      instance = { data: Math.random() };
    }
    return instance;
  };
})();

const instance1 = createSingleton();
console.log(instance1.data); // 0.057502791429981936

const instance2 = createSingleton();
console.log(instance2.data); // 0.057502791429981936

console.log(instance1 === instance2); // true

Functional programming with fp-ts

import { IO } from 'fp-ts/lib/IO';

type Singleton = {
  data: number
};

const createSingleton: IO<Singleton> = (() => {
  let instance: Singleton;
  return () => {
    if (!instance) {
      instance = { data: Math.random() };
    }
    return instance;
  };
})();

const instance1 = createSingleton();
console.log(instance1.data); // 0.3522236648406085

const instance2 = createSingleton();
console.log(instance2.data); // 0.3522236648406085

console.log(instance1 === instance2); // true

References:



P.S. My friend is actively seeking opportunities in Product Management, Marketing Operations, or Data Analytics.

He brings strong expertise in data analytics, mathematics, and finance. Currently based in Bangalore, India, he is open to both remote and in-office opportunities.

If you're looking for a driven professional with strong analytical skills and quick learning ability, please reach out to him directly:


#design  #patterns  #backend  #coding  #typescript  #nodejs  #fp-ts 

Suggested Reading

  • * How Postgres Triggers Can Simplify Your Backend Development

    * AWS Cloudwatch Monitoring & Alerts using Bash Scripts

    * MongoDB Auto Expire Documents using TTL Index

    * Getting Started with Express

    * Getting Started with Node.js Backend Development

  • Share this: