Skip to content

Instantly share code, notes, and snippets.

@shekhardtu
Created August 16, 2022 17:58
Show Gist options
  • Save shekhardtu/4cbf9e1e1e8598870e9e04f813c50a15 to your computer and use it in GitHub Desktop.
Save shekhardtu/4cbf9e1e1e8598870e9e04f813c50a15 to your computer and use it in GitHub Desktop.
Singleton Design Pattern with the help of car engine analogy.
// Design Patterns
// Singleton Design Pattern
const Singleton = (function () {
let instance;
function StartCar() {
this.gear = 0;
this.changeGear = function (gear) {
this.gear = gear;
};
this.getGear = function () {
return this.gear;
};
}
function createInstance() {
if (!instance) {
instance = new StartCar();
}
return instance;
}
return {
getInstance: createInstance
};
})();
let instance1 = Singleton.getInstance();
let instance2 = Singleton.getInstance();
instance1.changeGear(2);
instance2.changeGear(5);
console.log(instance1.getGear());
console.log(instance2.getGear());
console.log(instance1 === instance2); // print true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment