Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /***
- There are three parts to the Chain of Responsibility pattern:
- sender, receiver, and request. The sender makes the request.
- The receiver is a chain of 1 or more objects that choose whether to
- handle the request or pass it on. The request itself can be
- an object that encapsulates all the appropriate data.
- A sender sends the request to the first receiver object in
- the chain. The sender only knows about this first object and
- nothing about the other receivers. The first receiver either
- handles the request and/or passes it on to the next one in the
- chain. Each receiver only knows about the next receiver in the line.
- The request will keep going down the line until the request was handled
- or there are no more receivers to pass it on to, at which point either
- nothing happens or an error is thrown, depending on how you want it to work.
- ***/
- var MoneyStack = function(billSize) {
- this.billSize = billSize;
- this.next = null;
- }
- MoneyStack.prototype = {
- withdraw: function(amount) {
- var numOfBills = Math.floor(amount / this.billSize);
- if (numOfBills > 0) {
- this._ejectMoney(numOfBills);
- amount = amount - (this.billSize * numOfBills);
- }
- amount > 0 && this.next && this.next.withdraw(amount);
- },
- setNextStack: function(stack) {
- this.next = stack;
- },
- _ejectMoney: function(numOfBills) {
- console.log(numOfBills + " $" + this.billSize
- + " bill(s) has/have been spit out");
- }
- }
- var ATM = function() {
- var stack100 = new MoneyStack(100),
- stack50 = new MoneyStack(50),
- stack20 = new MoneyStack(20),
- stack10 = new MoneyStack(10),
- stack5 = new MoneyStack(5),
- stack1 = new MoneyStack(1);
- stack100.setNextStack(stack50);
- stack50.setNextStack(stack20);
- stack20.setNextStack(stack10);
- stack10.setNextStack(stack5);
- stack5.setNextStack(stack1);
- this.moneyStacks = stack100;
- }
- ATM.prototype.withdraw = function(amount) {
- this.moneyStacks.withdraw(amount);
- }
- var atm = new ATM();
- atm.withdraw(186);
- atm.withdraw(72);
Add Comment
Please, Sign In to add comment