-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton.js
More file actions
65 lines (55 loc) · 1.27 KB
/
singleton.js
File metadata and controls
65 lines (55 loc) · 1.27 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* @title: Singleton Pattern
* @description: Simple example
* @author: Thorsten Kober
* @email: [email protected]
*/
class Singleton {
constructor() {
if (this.instance) {
throw new Error('You can only create one instance!');
}
this._id = Math.random() * 1000;
}
get id() {
return this._id;
}
static getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
const FunctionalSingleton = (function () {
let instance;
function init() {
const id = Math.random() * 1000;
return {
getId: function () {
return id;
},
};
}
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
},
};
})();
// npx jest patterns/singleton.js
describe('patterns/singleton', () => {
it('should only use one instance for Singleton Class', () => {
const foo = Singleton.getInstance();
const bar = Singleton.getInstance();
expect(foo.id).toEqual(bar.id);
});
it('should only use one instance for FunctionalSingleton', () => {
const foo = FunctionalSingleton.getInstance();
const bar = FunctionalSingleton.getInstance();
expect(foo.getId()).toEqual(bar.getId());
});
});