singleton design pattern
javascript design pattern
by kazu69
JavaScript
const singleton = function() {
let instance;
function init() {
const privates = 'private variable';
function getPrivates() {
return privateVariable;
}
return {
props: 'public props',
getProps: function() {
return this.props
},
setProps: function(string) {
this.props = string;
return this;
},
getPrivate: function() {
return getPrivates.call(null);
}
}
}
const module = {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
}
return module;
}();
const s1 = singleton.getInstance();
const s2 = singleton.getInstance();
console.log(s1 === s2); // => true
s1.setProps('update');
console.log(s2.getProps()); // => update