// This object is the return value of init will be assigned to instance. return { // Public methods and variables publicVariable: 'I am public variable', publicMethod: () => { console.log('Public method'); }, }; };
// Public method to get the singleton instance constgetInstance = () => { if (!instance) { instance = init(); } return instance; };
// Expose the public method return { getInstance, }; })();
functioncreateInstance(name) { if (!instance) { // Init code goes here, If you want to exact init to a function, you must use createInstance.prototype.init = function(name){this.name = name}. This will make init public to every instance, it's bad idea! this.name = name; instance = this; }
return instance; }
return createInstance; })();
const a = newSingleton('zdd'); const b = newSingleton('ddz'); console.log(a === b); // true
下面是使用ES6的class来实现单例模式。代码更加简洁优雅。
Use class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSingleton { constructor() { if (!Singleton.instance) { Singleton.instance = this; // Your initialization code here } returnSingleton.instance; }
// Additional properties and methods can be added here }