1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| let order500 = function(orderType,pay,stock){ if(orderType === 1 && pay===true){ console.log('500元定金,100元优惠') }else{ return 'nextSuccessor' } } let order200 = function(orderType,pay,stock){ if(orderType === 2 && pay === true){ console.log('200元定金,50元优惠') }else{ return 'nextSuccessor' } } let orderNormal = function(orderType,pay,stock){ if(stock>0){ console.log('普通购买,无优惠') }else{ console.log('库存不足') } } let Chain = function(fn){ this.fn = fn; this.successor = null } Chain.prototype.setNextSuccessor = function(successor){ return this.successor = successor } Chain.prototype.passResquest = function(){ let ret = this.fn.apply(this,arguments) if(ret === 'nextSuccessor'){ return this.successor && this.successor.passResquest.apply(this.successor,arguments) } return ret } let chainOrder500 = new Chain(order500) let chainOrder200 = new Chain(order200) let chainOrderNormal = new Chain(orderNormal) chainOrder500.setNextSuccessor(chainOrder200) chainOrder200.setNextSuccessor(chainOrderNormal) chainOrder500.passResquest(1,true,500) chainOrder500.passResquest(2,true,500) chainOrder500.passResquest(3,true,500) chainOrder500.passResquest(1,false,0)
|