0%

职责链模式

职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间得到耦合关系,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止

灵活可拆分的职责链结点

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)
//console.log(ret)
if(ret === 'nextSuccessor'){
return this.successor && this.successor.passResquest.apply(this.successor,arguments)
}
return ret
}
let chainOrder500 = new Chain(order500)//500元定金,100元优惠
let chainOrder200 = new Chain(order200)
let chainOrderNormal = new Chain(orderNormal)
chainOrder500.setNextSuccessor(chainOrder200)
chainOrder200.setNextSuccessor(chainOrderNormal)
chainOrder500.passResquest(1,true,500)//500元定金,100元优惠
chainOrder500.passResquest(2,true,500)//走nextSuccessor,200元定金,50元优惠
chainOrder500.passResquest(3,true,500)//继续nextSuccessor,普通购买,无优惠
chainOrder500.passResquest(1,false,0)//一直nextSuccessor到库存不足

当要加入一个结点:

1
2
3
4
5
6
let order300 = function(){
...
}
chainOrder300 = new Chain(order300)
chainOrder500.setNextSuccessor(chainOrder300)
chainOrder300.setNextSuccessor(chainOrder200)

AOP模式实现职责链:

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
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('库存不足')
}
}
Function.prototype.after = function(fn){
let self = this
return function(){
let ret = self.apply(this,arguments)
if(ret === 'nextSuccessor'){
return fn.apply(this,arguments)
}
return ret;
}
}
let order = order500.after(order200).after(orderNormal)
order(1,true,500)
order(2,true,500)
order(1,false,500)