Singleton Pattern
suggest changeThe Singleton pattern restricts a service to one object. The first call to getInstance creates it. Later calls return that same object.
const Singleton = (function () {
// instance stores a reference to the Singleton
let instance;
function createInstance() {
// private variables and methods
const _privateVariable = 'I am a private variable';
function _privateMethod() {
console.log('I am a private method');
}
return {
// public methods and variables
publicMethod: function() {
console.log('I am a public method');
},
publicVariable: 'I am a public variable'
};
}
return {
// Get the Singleton instance if it exists
// or create one if doesn't
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
Usage:
// there is no existing instance of Singleton, so it will create one
const instance1 = Singleton.getInstance();
// there is an instance of Singleton, so it will return the reference to this one
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents