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.
– Wikipedia
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:
namespace SingletonPattern {
export class Singleton {
private static instance: Singleton;
private constructor() {}
static get Instance() {
if (this.instance === null || this.instance === undefined) {
this.instance = new Singleton();
}
return this.instance;
}
}
}
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:
/// <reference path="singleton.ts" />
namespace Demo {
function show() : void {
var singleton1 = SingletonPattern.Singleton.Instance;
var singleton2 = SingletonPattern.Singleton.Instance;
if (singleton1 === singleton2) {
console.log("two singletons are equivalent");
} else {
console.log("two singletons are not equivalent");
}
}
show();
}
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.
