Chain of Responsibility

A way of passing a request between a chain of objects

  • Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Insted chain the receiving objects and pass the request along the chain until an object handles it.

  • The chain of responsibility pattern creates a chain of receiver objects for a request.

  • In this pattern, normally each receiver contains reference to another receiver. If one receiver cannot handle the request then it passes the same request to the next receiver and so on.

  • One receiver in the chain handles a request or one or more receivers in the chain handles a request.

EX: // one or more receivers in the chain handles a request
var Request = function(amount) {
    this.amount = amount;
    console.log("Requested: $" + amount + "\n");
}
 
Request.prototype = {
    get: function(bill) {
        var count = Math.floor(this.amount / bill);
        this.amount -= count * bill;
        console.log("Dispense " + count + " $" + bill + " bills");
        return this;
    }
}

function run() {
    var request = new Request(378); 
    request.get(100).get(50).get(20).get(10).get(5).get(1);
}
run();

Last updated