How to implement Singleton in TypeScript
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one “single” instance. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton.
Disclaimer: This post is not to debate if Singleton Design Pattern is actually useful but how to implement it in TypeScript instead
Let’s take a look at how we usually define a class
I believe most of you guys are very familiar with the above template, basically we have a constructor
function which allows us to use the keyword new
to create a new instance.
Now if whenever I need to use this customized log
function, I can easily do that by declaring a new instance of Logger
class and invoke the function. But from the code readability wise, it doesn’t really make sense to have more than one instance of Logger
as there is no customization needed of the class, this is where Singleton design pattern comes into play.
In order to turn the above class into a Singleton class, first we need to disable anyone else to create a new instance of the Logger
class, and in order to do that, we can simply add a private
access modifier to our constructor function
As you can tell from the result, TypeScript immediately unhappy about line 9 when we try to instantiate the class.
Then, we can have a class property to store a single instance as below
private static instance: Logger;
Notice how we marked it as private static
so that this is a static properties and doesn’t allow access from anywhere else other than the class itself and it is of type Logger
.
Now that we have a class property ready to store the instance, we just need a method to create that single instance and store it
static getInstance() {
if (Logger.instance) {
return this.instance;
}
this.instance = new Logger();
return this.instance;
}
The code above is pretty self explanatory, basically we check if the class property instance
that we previously defined has any value, if there is, return that instance, else we create a new instance by new
keyword.
You might be wondering why we can have new
keyword here, it’s simply because getInstance
method is in Logger
class itself and hence it can access the constructor even-though it’s being marked as private
That’s it, we have converted our Logger
class to be a Singleton. Below is the full code of it
Thank you for reading and I hope this will helps you to be aware of more design patterns. For feedback and collaboration opportunities, I invite you to connect with me and let’s keep this conversation going!