Let's look at an example of a singleton.
Let us say I have a class named Accounting Department, and in real life scenario, there is only one accounting department. Hence, we need only one instance.
class AccountingDepartment {
private static accountingDepartment: AccountingDepartment;
private id: number;
private name: string;
static getInstance(): AccountingDepartment {
if (this.accountingDepartment) {
return this.accountingDepartment;
} else {
this.accountingDepartment = new AccountingDepartment(2, 'AD');
return this.accountingDepartment;
}
}
private constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
const accounting = AccountingDepartment.getInstance();
const accounting1 = AccountingDepartment.getInstance();
If you see, both accounting, as well as accounting1, will give you the same object in the console. So only one instance of a singleton is created.
Points to be noted here:
- A private constructor is being used here. So that no other class can access this constructor.
- The method is static as we need to access the method only through the class here.
- The getInstance method clearly states that if there is already an instance of the class, return that instance, only otherwise create a new instance and return it.
As only a Single Instance of the class is created, that is why it is a Singleton Pattern.