How to implement Singleton design pattern using TypeScript?

In this post, I’ll be explain how to implement Singleton design pattern using TypeScript. I’ll cover some other popular design patterns soon. This post is part of the Design Patterns in TypeScript series. If you would like to learn more, please subscribe to my website for new updates.

What is Singleton pattern?

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.

I’m using Visual Studio Code to run any code that you will see in this post.

Below is the code defined in Singleton.ts file:

Class instance and static members

Instance members of the class are visible on the object when it’s instantiated. Whereas static members of the class are visible on the class itself rather than on the instances.

Let me explain the code above. Singleton is the name of the class that has a private member named instance of type Singleton on line no. 3.

  • The instance method (get) on line no. 8 – check for whether the private member instance is null or undefined. If it is, then we new up this object.
  • In any case, the instance object value is returned.

In this way, this class is instantiated only once and is available on demand. If you would like a proof that any requested instances are equivalent, you should use following code:

The show method above requests the instance of Singleton class and then compares two objects. And the result is  that “two singletons are equivalent” always.

I hope this post properly explains how to implement Singleton design pattern using TypeScript. Please refer Design Patterns in TypeScript series to learn more about design patterns in TypeScript.

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger