Private Constructors
You can use a private constructor to create a class which cannot be instantiated from outside that class most especially when implementing the Singleton pattern or when you plan on making a class static.
Singleton Pattern
In this musing pattern, we make sure that there is one and only one object for a certain class instance as well as create an access point for this instance.
Example: In this use case, Singleton possesses a private constructor whose purpose is to prohibit direct instantiation whereas a way to get the one and only instance of the class is through the use of the function getInstance.
class Singleton {
private static instance: Singleton;
private constructor() {
// Private constructor ensures external
// code cannot instantiate this class
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public showMessage(): void {
console.log('Hello, Singleton!');
}
}
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();
singleton1.showMessage();
console.log(singleton1 === singleton2);
Output:
Hello, Singleton!
true
Static Class
An instance of a static class cannot be created and mostly includes static members.
Example: That is to say a private constructor here guarantees that instances of Utility cannot be created so that it becomes a static class with just static methods.
class Utility {
private constructor() {
// Prevent instantiation
}
public static logMessage(message: string): void {
console.log(message);
}
}
Utility.logMessage('This is a static method.');
Output:
This is a static method.
Private & Protected Constructors in TypeScript
Constructors are important in creating objects within classes while using TypeScript, in this by default constructors are public and thus can be called from any location. At times though, you may want to stop any other person from creating instances of your class – that is where we come across private and protected constructors.
Contact Us