Created
August 16, 2022 17:58
-
-
Save shekhardtu/4cbf9e1e1e8598870e9e04f813c50a15 to your computer and use it in GitHub Desktop.
Singleton Design Pattern with the help of car engine analogy.
This file contains 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
// 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