Skip to content

Instantly share code, notes, and snippets.

@midnqp
Last active November 6, 2023 04:26
Show Gist options
  • Save midnqp/06943134228c390b1114cbf70d00c571 to your computer and use it in GitHub Desktop.
Save midnqp/06943134228c390b1114cbf70d00c571 to your computer and use it in GitHub Desktop.
This is a singleton class implementation using `constructor()` in TypeScript.
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