Last active
October 2, 2017 04:33
-
-
Save hwindo/a74b77857db7c5e9b1a0ab451ef5f679 to your computer and use it in GitHub Desktop.
Singleton Pattern Example Printer
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
var printer = (function () { | |
var printerInstance; | |
function create() { | |
var turnedOn = false; | |
var paper = 5; | |
function print() { | |
// underlying printer mechanics | |
if (turnedOn) { | |
if (paper > 0) { | |
console.log('printing page...'); | |
paper -= 1; | |
} else { | |
console.log('ran out of paper'); | |
} | |
} else { | |
console.log('please turn on the printer first'); | |
} | |
} | |
function turnOn() { | |
console.log('warm up'); | |
console.log('check for paper'); | |
turnedOn = true; | |
} | |
function turnOff() { | |
console.log('turn led off'); | |
turnedOn = false; | |
} | |
function getStatus() { | |
console.log('printer status', {turnedOn: turnedOn, paper: paper}); | |
} | |
return { | |
// public + private states and behaviors | |
print: print, | |
turnOn: turnOn, | |
turnOff: turnOff, | |
getStatus: getStatus | |
}; | |
} | |
return { | |
getInstance: function () { | |
console.log(printerInstance); | |
if (!printerInstance) { | |
printerInstance = create(); | |
} | |
return printerInstance; | |
} | |
}; | |
})(); | |
// usage | |
// var officePrinter = printer.getInstance(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment