Last active
November 6, 2023 04:26
-
-
Save midnqp/06943134228c390b1114cbf70d00c571 to your computer and use it in GitHub Desktop.
This is a singleton class implementation using `constructor()` in TypeScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import crypto from 'node:crypto' | |
class Singleton { | |
private static instance?:Singleton|null | |
constructor() { | |
if (Singleton.instance) return Singleton.instance | |
if (Singleton.instance === undefined) { | |
Singleton.instance = null | |
Singleton.instance = new Singleton() | |
return Singleton.instance | |
} | |
} | |
uuid = crypto.randomUUID() | |
sayHello() { console.log('hello world', this.uuid) } | |
} | |
const one = new Singleton() | |
const two = new Singleton() | |
one.sayHello() // hello world e6d5790d-e960-445e-9774-71d0cca7548f 🔥 | |
two.sayHello() // hello world e6d5790d-e960-445e-9774-71d0cca7548f 🔥 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment