Creating a class that can only be initiated once — Singleton design pattern

Vikesh Mittal
Nov 12, 2020

--

How to create a class whose only one instance can exist?

We usually create instance of a class using new keyword. Each usage of new will create one instance of the class. Now we know that whenever we use new keyword, it calls the constructor of the class. What if we make the constructor private? But then how would we create even the first instance of the class.

Solution is to create a static method inside the class that will call private constructor and keep a tab on the instance of the class.

You can verify this by adding a public variable in the class and changing its value. See full code below:

--

--

Vikesh Mittal
Vikesh Mittal

Written by Vikesh Mittal

User Interface Architect | Passionate about Micro-frontends | Angular | React | https://vikeshmittal.com/

Responses (1)