Typescript Singleton pattern Implementation with example
- Admin
- Sep 20, 2023
- Typescript
In this blog post, learn the Singleton pattern in Typescript with examples.
Typescript Singleton Design pattern
Singleton is one of the simple and 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. Only Once an instance of the class is created in an application.
Every programming language provides an implementation for this pattern.
We can also implement the singleton pattern in Typescript. This is a simple creation pattern.
Typescript Singleton Pattern implementation
- Private modifier for the constructor, So that This class cannot be created by other classes.
- A private Static variable that always returns the instance of the same class
- A public static function that returns the instance of the class
Typescript Singleton pattern class example
Here are step by steps for singleton class
- Created Instance static member variables, which can be accessed using class instead of Object instances.
- And also added a private keyword added to a static member
- added private modifier to Constructor.
- Outside classes can not be created using the new operator.
- Declared static method or a function, which checks if the instance is null or undefined, creates an instance, and returns it, if already exists, just returned the instance.
Here is a code for the typescript singleton class example
.
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 we are ready to test the singleton class.
Here is a code testing the above 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
- Providing global access for object creation of a class, It always has one instance maintained.
- In applications, If you are implementing application caching, You will maintain only a single instance of a cache object always.
- Maintain a single instance when you are dealing with the global configuration in the application.
Conclusion
In this short tutorial, You learned about creating a singleton class and testing a singleton class for example.