This is part of the design pattern series in Typescript.
Code for this and other patterns can be found here: https://github.com/abhidatta0/Essential-design-patterns-in-Typescript
Why singleton is needed ?
There are some cases where we need to ensure only one instance of a class exists.
e.g: Thread pools, Caches, Settings.
Singleton Pattern ensures a class has only one instance, and provides a global point of access to it
Example
We know, every school has only one headmaster(or principal).
Irrespective of the situation , where the headmaster is called it should return the same person (or in code "instance").
Code
class Headmaster{
static uniqueInstance: Headmaster;
public readonly name = "Albert Einstein";
private constructor(){}
static getInstance(): Headmaster{
if(!Headmaster.uniqueInstance){
Headmaster.uniqueInstance = new Headmaster();
}
return Headmaster.uniqueInstance;
}
}
Let's break it down and explain.
-
static uniqueInstance: Headmaster
-> This is a static variable to hold our one instance. -
public readonly name = "Albert Einstein"
-> This is a property of the instance. For singleton, every object will have same property values.readonly
so it cannot be modified from outside. -
private constructor
-> Our constructor is made private ; only class itself can instantiate this class! -
static getInstance(): Headmaster
-> This is a static method which returns a instance of Headmaster class.We first check if theuniqueInstance
is null or not.- If uniqueInstance is null, we first create it via the private constructor and assign it to the uniqueInstance.
- If uniqueInstance isn't null , then it was previously created. We just fall through to the return statement.
Testing
const hm1 = Headmaster.getInstance(); // instance 1
const hm2 = Headmaster.getInstance(); // instance 2
console.log(hm1 === hm2); // will print true
Output:
Eager vs Lazy creation
If your application always creates and uses an instance of the Singleton class or the overhead of instance creation is not much, you may want to create the Singleton eagerly.
"Eager" means the instance will be created at the time of class creation in runtime.
This will require slight modification of above code.
class Headmaster_Eager{
static uniqueInstance: Headmaster_Eager = new Headmaster_Eager();
...
...
static getInstance(): Headmaster_Eager{
return Headmaster_Eager.uniqueInstance;
}
}
Here , no need to check if uniqueInstance is null or not in getInstance() method.
However, the eager way should be followed only if the object is always needed in your creation, otherwise it will waste memory.
That’s it 😅
Code for this and other patterns can be found here: https://github.com/abhidatta0/Essential-design-patterns-in-Typescript
Top comments (0)