Appearance
职责链模式
JS
JS
var order500 = function (orderType, pay, stock) {
if (orderType === 1 && pay === true) {
console.log('500')
} else {
return 'nextSuccessor' // 我也不知道下个节点是谁
}
}
var order200 = function (orderType, pay, stock) {
if (orderType === 2 && pay === true) {
console.log('200')
} else {
return 'nextSuccessor' // 我也不知道下个节点是谁
}
}
var orderNormal = function (orderType, pay, stock) {
if (stock > 0) {
console.log('普通购买,无优惠券')
} else {
console.log('手机库存不足');
}
}
// 构造函数
var Chain = function (fn) {
this.fn = fn
this.successor = null;
}
// 指定在链中的下一个节点
Chain.prototype.setNextSuccessor = function (successor) {
return this.successor = successor;
}
// 传递请求给某个节点
Chain.prototype.passRequest = function () {
var ret = this.fn.apply(this, arguments)
if (ret === 'nextSuccessor') {
return this.successor && this.successor.passRequest.apply(this.successor, arguments)
}
return ret
}
// AOE
Function.prototype.after = function (fn) {
var self = this;
return function () {
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);
order(2, true, 500);
order(1, false, 500);