-
-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathsingleton-concept.ts
More file actions
25 lines (20 loc) · 635 Bytes
/
Copy pathsingleton-concept.ts
File metadata and controls
25 lines (20 loc) · 635 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Singleton Concept Sample Code
export class Singleton {
// The Singleton Class
static instance: Singleton
id: number
constructor(id: number) {
this.id = id
if (Singleton.instance) {
return Singleton.instance
}
Singleton.instance = this
}
}
// The Client
// All uses of the singleton point to the same original object
const OBJECT1 = new Singleton(1) // setting its id property to 1
const OBJECT2 = new Singleton(2) // setting its id property to 2
console.log(OBJECT1 === OBJECT2) // = true
console.log(OBJECT1.id) // returns 1
console.log(OBJECT2.id) // returns 1