Last active
January 18, 2019 02:39
-
-
Save rxluz/2019fcb89d98622c71a3d5f6cbbc75b9 to your computer and use it in GitHub Desktop.
JS Design (Anti?)Patterns: Singleton, see more at https://medium.com/p/f375865bef10
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const utils = { | |
deepFreeze: obj => { | |
Object.freeze(obj); | |
Object.getOwnPropertyNames(obj).forEach(prop => { | |
const isNotNullOrUndefined = () => | |
obj[prop] !== null || typeof obj[prop] !== "undefined"; | |
const hasOwnProperty = () => obj.hasOwnProperty(prop); | |
const isNotFreeze = () => !Object.isFrozen(obj[prop]); | |
const isFunctionOrObject = () => | |
typeof obj[prop] === "function" || typeof obj[prop] === "object"; | |
if ( | |
isNotNullOrUndefined() && | |
hasOwnProperty() && | |
isNotFreeze() && | |
isFunctionOrObject() | |
) { | |
utils.deepFreeze(obj[prop]); | |
} | |
}); | |
return obj; | |
}, | |
}; | |
class ConfigParamsSingleton { | |
constructor() { | |
if (ConfigParamsSingleton.instance) { | |
return ConfigParamsSingleton.instance; | |
} | |
this.params = { | |
device: "iPhone", | |
useGPS: false, | |
useAcelerometer: true, | |
deviceUniqueID: Math.floor(Math.random() * 300), | |
}; | |
ConfigParamsSingleton.instance = this; | |
utils.deepFreeze(ConfigParamsSingleton.instance); | |
return ConfigParamsSingleton.instance; | |
} | |
getInstance() { | |
return this.constructor(); | |
} | |
getParams() { | |
return this.params; | |
} | |
} | |
const testSingleton = new ConfigParamsSingleton(); | |
testSingleton.params.device = "Android"; | |
testSingleton.params = { other: { complety: { different: "structure" } } }; | |
console.log(testSingleton.getParams()); | |
const otherTestsingleton = new ConfigParamsSingleton(); | |
console.log(otherTestsingleton.getParams()); | |
console.log(testSingleton === otherTestsingleton); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment