I was going through a Typescript repository today and I found all the classes were implemented in this fashion:-
export class ServiceClass {
private static instance: ServiceClass;
private constructor() {}
public static Instance(): ServiceClass {
if (!ServiceClass.instance) {
ServiceClass.instance = new ServiceClass();
}
return ServiceClass.instance;
}
// public static ServiceMethod1
// public static ServiceMethod2
// public static ServiceMethod3
}
The class methods were used like new ServiceClass.Instance().ServiceMethod1()
.
What I’m curious about is, what is the added benefit of having the Instance()
method? How would it be different if just the service methods were present in the class, and to access them you could do something like this:-
const obj = new ServiceClass();
obj.ServiceMethod1();
Is this some kind of design pattern?
1
This is the singleton pattern, it allows to access the same instance from everywhere without having to pass a reference.