3 Ways to Implement the Singleton Pattern in TypeScript With Node.js
The Problem — Logging Example

Here’s an example problem: I have a Node.js app for payment processing that uses a Logger class. We want to keep a single logger instance in this example and ensure the Logger state is shared across the Payment app. To keep things simple, let’s say that we need to ensure that the logger needs to keep track of the total number of logged messages within the app. Ensuring that the counter is tracked globally within the app means that we will need a singleton class to achieve this.

A high-level diagram of the sample app by the author.

Let’s go through each of the classes that we will be using.

Logger class: Logger.ts

A basic logger class that allows its clients to log a message with a timestamp. It also allows the client to retrieve the total number of logged messages.

Payment class: Payment.ts

The Payment processing class processes the payment. It logs the payment instantiation and payment processing:

The entry point of the app: index.ts

The entry point creates an instance of the Logger class and processes the payment. It also processes the payment through the Payment class:

If we run the code above, we will get the following output:

# Run the app

tsc && node dist/creational/singleton/problem/index.js

Output screenshot by the author.

Notice that the log count stays at 1 despite showing 3 logged messages. The count remains at 1 because a new instance of Logger is created in index.ts and Payment.ts separately. The log count here only represents what’s logged in index.ts . However, we also want to include the number of logged messages in the Payment class.

Here are different ways to solve this problem by using a singleton design pattern.
['Ardy Dedase']
['Technology', 'Startup', 'Software Development', 'JavaScript', 'Programming']