Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Tue Mar 21 2023

Singleton pattern in TypeScript

In todays post we will explore the Singleton pattern, and how we can implement it in TypeScript.

What is Singleton?

Singleton is a design pattern in object oriented programming. What is specific about Singleton is that it restricts the creation of an instance of the class to only be one.

A common use case of a Singleton is a Logging class that should be easily accessible accross the application. In this guide, we will create our own Logging class and invoke it in another class.

Creating our Singleton class

We will show two approaches on how the Singleton can be implemented

Approach 1

Implementation of the Logger class:

class Logger { info(infoMsg: string) { console.info(`Logging some information`, infoMsg); } error(errorMsg: string) { console.error(`Logging an error`, errorMsg); } warning(warning: string) { console.warn(`Logging a warning`, warning); } } // This makes the class always being created only once export default new Logger();

Using the Logger:

import Logger from "./Logger"; Logger.info("Some info"); Logger.warning("Some warning"); Logger.error("Some error");
Approach 2

This is more the traditional way of doing it, e.g in Java and other OOP languages

export default class Logger { private static instance: Logger; // Prevents any creation of objects outside the class private constructor() {} // This is the function that will handle the creation of the object. And it will make sure to only create one object public static getInstance(): Logger { if (!Logger.instance) { Logger.instance = new Logger(); } return Logger.instance; } public info(infoMsg: string) { console.info(`Logging some information`, infoMsg); } public error(errorMsg: string) { console.error(`Logging an error`, errorMsg); } public warning(warning: string) { console.warn(`Logging a warning`, warning); } }

Using the Logger

import Logger from "./Logger"; Logger.getInstance().info("Info"); Logger.getInstance().warning("Warning"); Logger.getInstance().error("Error");

Conclusion

The Singleton pattern is considered by some to be an anti-pattern due to that it introduces a global state in your application. This can cause some difficulties in for example unit testing. It also live on forever and violates the single purpose principle.

However, like a logger, it makes sense to use this pattern. It creates single access point to it, it ensures that only one instance is created and can be very handy in some situations.

What do you think of the Singleton pattern?
signatureTue Mar 21 2023
See all our articles