JS设计模式-责任链模式
1.
看以下代码
function distributePrizes(payMethod, isPay, prizesCount) {
//充值五百
if (payMethod === 500) {
if (isPay) {
console.log("恭喜获得100块礼品卷");
} else {
if (prizesCount) {
console.log("恭喜获得10块礼品卷");
} else {
console.log("抱歉,礼品券库存不足");
}
}
//充值两百
} else if (payMethod === 200) {
if (isPay) {
console.log("恭喜获得20块礼品卷");
} else {
if (prizesCount) {
console.log("恭喜获得10块礼品卷");
} else {
console.log("抱歉,礼品券库存不足");
}
}
//不充值
} else {
if (prizesCount) {
console.log("恭喜获得10块礼品卷");
} else {
console.log("抱歉,礼品券库存不足");
}
}
}
各种嵌套的if-else if-else让人读起来很累。不难想象的是参数通过if-elseif-else不断的判断从而向下传递,那么可以采用责任链的模式(或者说链表)来进行优化,从而满足开放封闭原则(对拓展开放修改封闭)和单一职责原则
2.
function pay500(payMethod, isPay, prizesCount) {
if (isPay && payMethod === 500) {
console.log("恭喜获得100块礼品卷");
} else {
return "goNext";
}
}
function pay200(payMethod, isPay, prizesCount) {
if (isPay && payMethod === 200) {
console.log("恭喜获得20块礼品卷");
} else {
return "goNext";
}
}
function nexType(payMethod, isPay, prizesCount) {
if (prizesCount) {
console.log("恭喜获得10块礼品卷");
} else {
console.log("抱歉,礼品券库存不足");
}
}
function testPayChain(fn){
this.fn = fn
this.nextChain = null
}
testPayChain.prototype.distributePrizes = function(){
var mark = this.fn.apply(this,arguments)
return mark === 'goNext' && this.nextChain.distributePrizes.apply(this.nextChain,arguments)
}
var head = new testPayChain(function(payMethod, isPay, prizesCount){return 'goNext'})
var chain500 = new testPayChain(pay500)
var chain200 = new testPayChain(pay200)
var chainNexType = new testPayChain(nexType)
head.nextChain = chain500
chain500.nextChain = chain200
chain200.nextChain = chainNexType
head.distributePrizes(500,true,500)
head.distributePrizes(200,true,500)
head.distributePrizes(500,false,500)
head.distributePrizes(200,false,0)
3.存在的问题
1.当链条很长的时候存在性能问题
2.当存在异步函数的时候即无法采用该方法