var orderType = function(orderType, pay, stock) {
if( orderType === 1 ) {
if( pay === true ) {
console.log("500元定金预购,得到100优惠券");
} else {
if ( stock > 0 ) {
console.log("普通购买,无优惠券");
} else {
console.log("手机库存不足");
}
}
} else if( orderType === 2 ) {
if( pay === true ) {
console.log("200元定金预购,得到50优惠券");
} else {
if ( stock > 0 ) {
console.log("普通购买,无优惠券");
} else {
console.log("手机库存不足");
}
}
} else if( orderType === 3 ) {
if ( stock > 0 ) {
console.log("普通购买,无优惠券");
} else {
console.log("手机库存不足");
}
}
}
// 职责链
// 500 元订单
var order500 = function(orderType, pay, stock){
if( orderType === 1 && pay === true) {
console.log("500元定金预购,得到100优惠券");
} else {
order200(orderType, pay, stock)
}
}
// 200 元订单
var order200 = function(orderType, pay, stock){
if( orderType === 2 && pay === true) {
console.log("200元定金预购,得到50优惠券");
} else {
orderNormal(orderType, pay, stock)
}
}
// 普通购买订单
var orderNormal = function(orderType, pay, stock){
if ( stock > 0 ) {
console.log("普通购买,无优惠券");
} else {
console.log("手机库存不足");
}
}
// 灵活可拆分的职责链节点(解耦))
// 500 元订单
var order500m = function(orderType, pay, stock){
if( orderType === 1 && pay === true) {
console.log("500元定金预购,得到100优惠券");
} else {
return 'nextSuccessor';
}
}
// 200 元订单
var order200m = function(orderType, pay, stock){
if( orderType === 2 && pay === true) {
console.log("200元定金预购,得到50优惠券");
} else {
return 'nextSuccessor';
}
}
// 普通购买订单
var orderNormalm = 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;
}
// 包装职责链节点
var chainOrder500 = new Chain(order500m);
var chainOrder200 = new Chain(order200m);
var chainOrderNormal = new Chain(orderNormalm);
// 指定节点在职责链中的顺序
chainOrder500.setNextSuccessor( chainOrder200 );
chainOrder200.setNextSuccessor( chainOrderNormal );
// 请求传递给第一个节点
chainOrder500.passRequest(2, true, 0);
console