On this put up, we are going to learn to create a singleton class utilizing Typescript.
Singleton sample
The Singleton design sample is a really well-known sample utilized in software program engineering that ensures we solely have one occasion, or a single occasion, of a category in our utility and likewise supplies a simple strategy to get entry to that object.
Implementation
So as to implement a Singleton class we principally have to observe these two steps:
- Make the category constructor non-public, stopping from utilizing the
new
operator to create objects of that class. - Create a static technique to instantiate our single occasion and make it accessible by way of the appliance.
Here is a Lonely class which implements the singleton sample:
class Lonely {
non-public static occasion: Lonely;
non-public constructor() {}
static getInstance() {
if (this.occasion) {
return this.occasion;
}
this.occasion = new Lonely();
return this.occasion;
}
}
Breaking down the code:
First, we outline an occasion
property:
non-public static occasion: Lonely;
This property holds the one occasion of our Lonely class. It is non-public and static because it should not be accessible from its objects (or from its solely object in our singleton case).
Then, we have now the constructor:
non-public constructor() {}
This is among the key items the place we make the constructor non-public, so if we attempt to instantiate new object of Lonely with const newInstance = new Lonely()
we get an error: Constructor of sophistication 'Lonely' is non-public and solely accessible throughout the class declaration.
And eventually, we have now the getInstance technique.
static getInstance() {
if (this.occasion) {
return this.occasion;
}
this.occasion = new Lonely();
return this.occasion;
}
We needn’t identify it getInstance nevertheless it’s a superb observe following the naming conference so it helps our code to be broadly comprehensible.
What we should do is make it static and public, since will probably be the purpose of entry to creating the single occasion of our class.
The logic is fairly easy: if we have already got an occasion of our class we simply return it; if it is the primary instantiation then we create our object calling the non-public constructor new Lonely()
and return it.
We might additionally use the Lonely
class identify as a substitute of the this
key phrase:
static getInstance() {
if (Lonely.occasion) {
return Lonely.occasion;
}
Lonely.occasion = new Lonely();
return Lonely.occasion;
}
Accessing our single occasion
To entry the one object of our Lonely class we simply have to name its getInstance technique:
const l1 = Lonely.getInstance();
const l2 = Lonely.getInstance();
console.log(l1 === l2); // return true