// 500 元客户订单 var order500 = function (orderType,pay,stock) { if(orderType === 1 && pay){ console.log('500 rmb deposit, get 100 coupon ') } else { return'nextSuccessor'// unknow the next node but always pass to next. } };
// 200 元客户订单 var order200 = function (orderType,pay,stock) { if(orderType === 2 && pay){ console.log('200 rmb deposit , get 50 coupon') } else{ return'nextSuccessor'; } };
// 无预约客户订单 var orderNormal = function (orderType,pay,stock) { if(stock > 0){ console.log('normal buy no coupon') } else{ console.log('the stock lack') } };
// 定制职责链对象(作用是形成订单职责链) var Chain = function (fn) { this.fn = fn; this.successor = null; }; // 设置职责链 Chain.prototype.setNextSuccessor = function (successor) { returnthis.successor = successor; }; // 设置每个节点的调用方式 Chain.prototype.passRequest = function () { var ret = this.fn.apply(this.arguments); if(ret === 'nextSuccessor'){ returnthis.successor && this.successor.passRequest.apply(this.successor,arguments) } return ret; };
// 现在我们把3个订单函数分别包装成职责链的节点 var chainOrder500 = new Chain(order500); var chainOrder200 = new Chain(order200); var chainOrderNormal = new Chain(orderNormal);