How you can achieve a Singleton using a module?

Using a module to implement a Singleton in TypeScript is a simple and effective way to ensure that only one instance of a resource or service exists. Modules in TypeScript are inherently Singleton because they are loaded once and cached by the runtime.

Implementation

// singletonModule.ts
export const SingletonModule = {
// Private property (emulated through module scope)
_value: 0,

// Public method to access or modify the shared resource
increment: () => {
SingletonModule._value += 1;
return SingletonModule._value;
},

getValue: () => {
return SingletonModule._value;
}
};

Usage

// main.ts
import { SingletonModule } from './singletonModule';

// Access the Singleton instance
console.log(SingletonModule.getValue()); // Output: 0

SingletonModule.increment();
console.log(SingletonModule.getValue()); // Output: 1

// Incrementing again from another part of the application
import { SingletonModule as AnotherReference } from './singletonModule';
AnotherReference.increment();
console.log(AnotherReference.getValue()); // Output: 2

// Both references are the same instance
console.log(SingletonModule === AnotherReference); // Output: true