Skip to content

Instantly share code, notes, and snippets.

@OriginUnknown
Last active August 29, 2015 14:23
Show Gist options
  • Save OriginUnknown/9432512f7ecb3f80a770 to your computer and use it in GitHub Desktop.
Save OriginUnknown/9432512f7ecb3f80a770 to your computer and use it in GitHub Desktop.
JavaScript OOP Design Patterns - Chain of Responsibility 2.0.1 {Cash Machine}
<!doctype html>
<html lang="en">
<head>
<title>Chain of Responsibility pattern - Cash Machine Scenario</title>
</head>
<body>
<script type="text/javascript">
var ATM = (function(){
var self = {}, _log = "", _amount = "",
Note = function ( note ) {
var successor = null, numOfNotes,
setSuccessor = function ( nextInChain ) {
successor = nextInChain || null;
},
handleRequest = function ( amount ) {
if ( (amount % 5) === 0 ) {//check that the amount requested is divisible by 5
numOfNotes = Math.floor( amount / note );//find out the number of notes to dispense
if ( numOfNotes > 0 ) {//if there's any notes to dispense
_log += "Number of \u00A3" + note + " notes dispensed: " + numOfNotes + "\n";
amount -= (numOfNotes * note);//deduct the amount the number of bills dispensed equates to from the amount passed in
}
if ( amount > 0 && successor ) {//if there's still money to dispense and a handler defined as next in the chain, pass the request on
successor.dispense( amount );
} else {
console.log("You've requested \u00A3" +_amount.toString());
console.log( _log );
console.log( "Your request is complete." );
_log = "", _amount = "";//reset the _log and _amount variables
}
} else {//if the amount requested isn't divisible by 5
console.log( "It has not been possible to dispense \u00A3" + amount + " from this cash machine." );
}
};
return {
"setSuccessor": setSuccessor,
"dispense": handleRequest
}
},
//Initialise the Note class for the relevant notes that will be dispensed
fifty = Note(50), twenty = Note(20), ten = Note(10), five = Note(5);
//Organise the chain of responsibility
fifty.setSuccessor( twenty );
twenty.setSuccessor( ten );
ten.setSuccessor( five );
//return public interface
self.amount = function(request){
_amount = request;
fifty.dispense(request);
};
return self;
})();
console.log(ATM.amount(235));
console.log(ATM.amount(450));
console.log(ATM.amount(124));
console.log(ATM.amount(775));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment