Design Patterns in TypeScript: Singleton
TypeScript is a superset of JavaScript that adds optional static typing and other features to the language. TypeScript can be used to write complex applications, and design patterns can be used to structure and organize code in a reusable and maintainable way.
Singleton
The singleton design pattern is used when you want to ensure that only one instance of a particular class is created throughout the lifetime of a program, and that instance can be accessed globally.
Simple Implementation
In this section, we consider the implementation of Singleton using TypeScript.
1. Create the Singleton class with static private property of the Singleton class:
class Singleton {
private static _instance: Singleton
}
2. Add a private constructor to avoid creating a direct instance from the class.
private constructor() {}
3. Add a method to create and access the class instance. This method creates a new class instance when the first time it uses. Otherwise, it returns the already created instance.
static get instance(): Singleton {
if (!this._instance) {
this._instance = new Singleton()
}
return this._instance
}
Complete code:
class Singleton {
private static _instance: Singleton
private constructor() {}
static get instance(): Singleton {
if (!this._instance) {
this._instance = new Singleton()
}
return this._instance
}
}
Advance implementation
In this section, Singleton implemented using TypeScript with asynchronous initialization. Consider the following code:
class Singleton {
private static _instance: Singleton
private data: string
private constructor() {}
public static async getInstance(): Promise<Singleton> {
if (!Singleton._instance) {
Singleton._instance = new Singleton()
Singleton._instance.data = await Singleton._instance.loadData()
}
return Singleton._instance
}
private async loadData(): Promise<string> {
// simulate async data loading
return new Promise<string>((resolve, reject) => {
setTimeout(() => {
resolve("Some data loaded asynchronously")
}, 1000);
});
}
public getData(): string {
return this.data
}
}
The getInstance
method is static and async, which returns a Promise that resolves to the singleton instance. It first checks whether the instance variable is null and initializes it by calling the constructor and loading the data asynchronously.
The loadData
the method simulates some asynchronous data loading by returning a Promise that resolves to some string after a timeout.
In this article, we discuss the Singleton design pattern in TypeScript. There are many more. Let’s discuss others in the next articles.
You Don’t Need to ‘Reinvent the Wheel’