Skip to content

Instantly share code, notes, and snippets.

@C-Rodg
Created April 7, 2017 17:38
Show Gist options
  • Save C-Rodg/ce27af01ab2d7b486220effd42fae773 to your computer and use it in GitHub Desktop.
Save C-Rodg/ce27af01ab2d7b486220effd42fae773 to your computer and use it in GitHub Desktop.
Singleton pattern implemented with Javascript.
const printer = (function() {
let printerInstance;
function create() {
function print() {
console.log("Printing document...");
}
function turnOn() {
console.log("Turning on, checking for paper...");
}
return {
print: print,
turnOn: turnOn
};
}
return {
getInstance: function() {
if (!printerInstance) {
printerInstance = create();
}
return printerInstance;
}
};
})();
const myPrinter = printer.getInstance();
myPrinter.turnOn();
myPrinter.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment