What exactly is a singleton?
Singleton is a design pattern which allows you to create only one instance of a class and no more.
How can I implement singleton?
Best way to understand a concept is using an example.
So, let's say I want to create a class which can have only one instance and I want this class to have two variables: id and name, and one method which logs those variables.
I will first create a class named MyInfo
and add a private variable called as instance
which has a type of it's own class.
As the name justifies itself, we will use this instance
variable to store instance of our class.
class MyInfo {
private static instance: MyInfo;
}
I will then create a private constructor method. The reason for making the constructor private is to prevent usage of new
to create a new instance of class outside the class.
class MyInfo {
private static instance: MyInfo;
private constructor(public id: number, public name: string) {}
}
Since we have made our constructor private, we need a way to make an instance of our class.
We do this by making a static method which checks if the class already has an instance. If our class already has an instance we return the same instance and if not we create a new instance and store that instance in our instance
variable and later return the same.
We can do this as follows.
class MyInfo {
private static instance: MyInfo;
private constructor(public id: number, public name: string) {}
static getInstance() {
if (this.instance) {
return this.instance;
} else {
this.instance = new MyInfo(1, "Musaib");
return this.instance;
}
}
}
We can now implement getDetails
method which logs our name
and id
.
class MyInfo {
private static instance: MyInfo;
private constructor(public id: number, public name: string) {}
static getInstance() {
if (this.instance) {
return this.instance;
} else {
this.instance = new MyInfo(1, "Musaib");
return this.instance;
}
}
getDetails() {
console.log(`Hi i'm ${this.name} and my id is ${this.id}`);
}
}
Now let's check if we can make an instance and get our details.
const obj = MyInfo.getInstance();
console.log(obj);
obj.getDetails();
Here's the output to our code ๐
What if I try to make another instance using the same getInstance
method?
As a matter of fact you can totally do that!
BUT, the new instance that you have created points to the same memory location as our OLD instance๐.
What if I still use new
outside the class?
If you try to make a new instance of the class outside the class using new
, you get an error saying Constructor of class 'MyInfo' is private and only accessible within the class declaration.ts(2673)
and hence we cannot make a new instance.
Top comments (0)