• 职责链模式的定义:使用多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系,将这些对象连成一条链,
  • 并沿着这条链条传递下去,直到有一个对象处理它为止。
var order500 = function (ordertype, pay, stock) {
if (ordertype === 1 && pay == true) {
console.log("500元定金,100元优惠券");
} else {
return 'next';
}
}; var order200 = function (ordertype, pay, stock) {
if (ordertype === 2 && pay == true) {
console.log("200元定金,50元优惠券");
} else {
return 'next';
}
}; 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.setNext = function (succ) {
this.successor = succ;
};
Chain.prototype.passRequest = function () {
var ret = this.fn.apply(this, arguments);
if (ret === 'next') {
return this.successor && this.successor.passRequest.apply(this.successor, arguments);
}
return ret;
}; var chainorder500 = new Chain(order500);
var chainorder200 = new Chain(order200);
var chainorderNormal = new Chain(orderNormal); chainorder500.setNext(chainorder200);
chainorder200.setNext(chainorderNormal); chainorder500.passRequest(1, true, 500);
chainorder500.passRequest(2, true, 500);
chainorder500.passRequest(3, true, 500);
chainorder500.passRequest(1, false, 0);
  • 通过职责链模式,我们可以灵活的添加,移除修改链中的节点顺序。
  • 下面我们用AOP实现职责链
 Function.prototype.after = function (fn) {
var self = this;
return function () {
var ret = self.apply(this, arguments);
if (ret === 'next') {
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);

JS模式--职责链模式-LMLPHP

05-06 18:14