TypeScript Singleton design pattern example
TypeScript Classes and OOP : Exercise-23 with Solution
Write a TypeScript class called Singleton that follows the Singleton design pattern. The class should have a private static instance of itself and a static method getInstance() that returns the instance. Ensure that only one instance of the class can be created. Test the Singleton pattern by creating multiple instances and checking if they are the same instance.
Sample Solution:
TypeScript Code:
Explanations:
In the exercise above -
- First, define a "Singleton" class with a private static property 'instance' initialized to 'null'.
- The constructor of the class is made private to prevent external instantiation of the class.
- Next, implement a static method "getInstance()" that checks if an instance of the class already exists. If an instance doesn't exist, it creates a new one; otherwise, it returns the existing instance.
- In the testing section, we create two instances (instance1 and instance2) of the "Singleton" class using the "getInstance()" method. We then check if they are the same instance by comparing their references using the === operator.
Output:
true
TypeScript Editor:
Previous: TypeScript Math utility class for mathematical operations.
Next: TypeScript utility functions example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics