Design Pattern: Singleton Pattern

Improved from module pattern :D

Code

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
const anph = (function () {
let instance;// -> undefined
function init() {
//properties
const a = 'A', n = 'n', p = 'p', h = 'h';
//method
getA = () => a;
getN = () => n;
getP = () => p;
getH = () => h;
getAnph = () => getA() + n + p + h;
//what to public
return { getAnph, getP };

}
return {
getInstance: function () {
if (!instance) //make sure only 1 object created
instance = init();
return instance;
}
}
})();


// console.log(anph.getInstance().getA()); // anph.getInstance(...).getA is not a function

console.log(anph.getInstance().getAnph());//Anph

Demo

Singleton Pattern