var order500 = function (orderType, pay, stock) { if (oderType === 1 && pay) { console.log('500 元定金预购, 得到 100 元优惠券') } else { return'nextSuccessor'// 我不知道下一个节点是谁,反正把请求往后面传递 } }
var order200 = function (orderType, pay, stock) { if (oderType === 2 && pay) { console.log('200 元定金预购, 得到 50 元优惠券') } else { return'nextSuccessor' } }
var orderNormal = function (orderType, pay, stock) { if (stock > 0) { console.log('普通购买,无优惠券') } else { console.log('手机库存不足') } }
// 定义构造函数Chain,负责链式传递 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 }
1 2 3 4 5 6 7 8 9
// 包装节点 var chainOrder500 = new Chain(order500) var chainOrder200 = new Chain(order200) var chainOrderNormal = new Chain(orderNormal) // 指定节点在职责链中的顺序 chainOrder500.setNextSuccessor(chainOrder200) chainOrder200.setNextSuccessor(chainOrderNormal) // 使用 chainOrder500.passRequest(1, true, 500) // 输出: 500 元定金预购, 得到 100 优惠券
Function.prototype.after = function (fn) { var self = this returnfunction () { var ret = self.apply(this, arguments) if (ret === 'nextSuccessor') { return fn.apply(this, arguments) } return ret } }
var order = order500.after(order200).after(orderNormal) order( 1, true, 500 ) // 输出:500 元定金预购,得到 100 优惠券