-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleton.ts
52 lines (40 loc) · 1.33 KB
/
singleton.ts
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Ensure that only one instance of a class is created
Provide a global point of access to the object
*/
module Singleton {
export class SingletonClass {
private static instance: SingletonClass = new SingletonClass();
private count: number = 0;
constructor() {
if (SingletonClass.instance) {
throw new Error("Error constructor should not be used directly. Use getInstance() instead.");
}
SingletonClass.instance = this;
}
public static getInstance(): SingletonClass {
if (SingletonClass.instance === null) {
SingletonClass.instance = new SingletonClass();
}
return SingletonClass.instance;
}
public setCount(value: number): void {
this.count = value;
}
public getCount(): number {
return this.count;
}
public add(value: number): void {
this.count += value;
}
public remove(value: number): void {
this.count -= value;
}
}
}
var counter = Singleton.SingletonClass.getInstance();
var counter2 = Singleton.SingletonClass.getInstance();
counter.setCount(20);
counter2.add(5);
counter.remove(15);
write(counter.getCount());