w3resource

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:

class Singleton {
  private static instance: Singleton | null = null;

  private constructor() {
    // Private constructor to prevent external instantiation
  }

  static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }
}

// Testing the Singleton pattern
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // Output: true (Both instances are the same)

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:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/typescript-exercises/typescript-class-and-oop-exercise-23.php