-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsingleton1.js
More file actions
68 lines (58 loc) · 1.9 KB
/
Copy pathsingleton1.js
File metadata and controls
68 lines (58 loc) · 1.9 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
66
67
68
/* --Singleton with getInstance and init --
good:
* real singleton
* the singleton is not created until we call game.getInstance for the first time
* delayed creation
* this may help save memory before we use it
* especially if we need to define the singleton long before using it
* (note that good js engines can optimize out such things in the other
* singleton techniques by temporary generating equivalent code)
* can be extended with special sublassing techniques (not recommended)
* the singleton could contain metadata in at the right place
bad:
* heavy
* at the end we have an instance + singleton but we only really want the instance
* if we want the singleton to be created with arguments we have to
* pipeline parameters trough getInstance, then init, and not at the top
* internally the instance is not a const
conclusion:
* hard to read
* and taking advantage of the good points is rare in practice
*/
const game = (function () {
"use strict";
// reference to the singleton
let thisGame;
// define init
const init = function () {
// private members
let score = 0;
// public members
const setScore = function (newScore) {
score = newScore;
};
const isGameOver = function () {
return score > 100;
};
// expose public members only
return {
setScore,
isGameOver
};
};
// we do not return the singleton but a wrapper which wraps a function
// to get the instance out of it
return {
getInstance: function () {
// return the singleton, create one if it does not exist yet
if (!thisGame) {
thisGame = init();
}
return thisGame;
}/*, we could include metadata here */
};
}());
/*usage:
const game1 = game.getInstance();
game1.setScore(30);
*/