Typescript Singleton pattern Implementation with example

In this blog post, you will learn about the Singleton pattern in TypeScript with examples.

TypeScript Singleton Design Pattern

The Singleton pattern is one of the simplest and most frequently used design patterns in application development. It is a creational design pattern that enables the creation of a single instance or object of a class in the application, ensuring that only one instance of the class is created.

Every programming language provides an implementation for this pattern, and TypeScript is no exception. Implementing the singleton pattern in TypeScript is straightforward.

TypeScript Singleton Pattern Implementation

Here are the key functions of implementing the Singleton pattern in TypeScript:

  • Using the private modifier for the constructor to prevent the class from being instantiated by other classes.
  • Defining a private static variable that always returns the instance of the same class.
  • Creating a public static function that returns the instance of the class.

TypeScript Singleton Pattern Class Example

Here are the steps for implementing a singleton class:

  • Define a static member variable to hold the instance, which can be accessed using the class instead of object instances.
  • Use the private keyword to restrict access to the static member.
  • Add a private modifier to the constructor to prevent instantiation from outside classes.
  • Prevent instantiation using the new operator by making the constructor private.
  • Declare a static method or function that checks if the instance exists, creates it if it doesn’t, and returns it.

Below is an example code for the TypeScript singleton class.

export default class SingletonClass {
  private static instance?: SingletonClass;
  private constructor() {}
  public static getInstance() {
    if (!SingletonClass.instance) {
      SingletonClass.instance = new SingletonClass();
    }
    return SingletonClass.instance;
  }
}

We have created a singleton class, Now, let’s test the singleton class:

let instance1 = new SingletonClass(); // This gives compilation error

let instance2 = SingletonClass.getInstance();
let instance3 = SingletonClass.getInstance();

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

If you create an object using the new operator, it gives compilation error - constructor of class ‘SingletonClass’ is private only accessible within class declaration.

Use Cases and Advantages

The Singleton pattern offers several advantages and can be used in various scenarios.

  • Providing global access for object creation of a class, ensuring only one instance is maintained.
  • Implementing application caching where only a single instance of a cache object is maintained.
  • Managing global configuration in the application by maintaining a single instance.

Conclusion

In this tutorial, you learned how to create and test a singleton class in TypeScript.