Guest User

Untitled

a guest
Apr 25th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. /***
  2. There are three parts to the Chain of Responsibility pattern:
  3. sender, receiver, and request. The sender makes the request.
  4. The receiver is a chain of 1 or more objects that choose whether to
  5. handle the request or pass it on. The request itself can be
  6. an object that encapsulates all the appropriate data.
  7. A sender sends the request to the first receiver object in
  8. the chain. The sender only knows about this first object and
  9. nothing about the other receivers. The first receiver either
  10. handles the request and/or passes it on to the next one in the
  11. chain. Each receiver only knows about the next receiver in the line.
  12. The request will keep going down the line until the request was handled
  13. or there are no more receivers to pass it on to, at which point either
  14. nothing happens or an error is thrown, depending on how you want it to work.
  15. ***/
  16.  
  17. var MoneyStack = function(billSize) {
  18. this.billSize = billSize;
  19. this.next = null;
  20. }
  21.  
  22. MoneyStack.prototype = {
  23. withdraw: function(amount) {
  24. var numOfBills = Math.floor(amount / this.billSize);
  25. if (numOfBills > 0) {
  26. this._ejectMoney(numOfBills);
  27. amount = amount - (this.billSize * numOfBills);
  28. }
  29. amount > 0 && this.next && this.next.withdraw(amount);
  30. },
  31. setNextStack: function(stack) {
  32. this.next = stack;
  33. },
  34. _ejectMoney: function(numOfBills) {
  35. console.log(numOfBills + " $" + this.billSize
  36. + " bill(s) has/have been spit out");
  37. }
  38. }
  39.  
  40.  
  41. var ATM = function() {
  42. var stack100 = new MoneyStack(100),
  43. stack50 = new MoneyStack(50),
  44. stack20 = new MoneyStack(20),
  45. stack10 = new MoneyStack(10),
  46. stack5 = new MoneyStack(5),
  47. stack1 = new MoneyStack(1);
  48. stack100.setNextStack(stack50);
  49. stack50.setNextStack(stack20);
  50. stack20.setNextStack(stack10);
  51. stack10.setNextStack(stack5);
  52. stack5.setNextStack(stack1);
  53. this.moneyStacks = stack100;
  54. }
  55.  
  56. ATM.prototype.withdraw = function(amount) {
  57. this.moneyStacks.withdraw(amount);
  58. }
  59. var atm = new ATM();
  60. atm.withdraw(186);
  61.  
  62. atm.withdraw(72);
Add Comment
Please, Sign In to add comment