什么是职责链模式

面向对象例子:

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
46
47
48
49
50
51
52
53
export class Vip5{
constructor() {
this.level = 5;
}

getDiscount(pay, level) {
if (level === this.level) {
console.log(pay * 0.5);
} else {
this.nextChain.getDiscount(pay, level);
}
}

setNextChain(obj) {
this.nextChain = obj;
}
}

export class Vip3{
constructor() {
this.level = 3;
}

getDiscount(pay, level) {
if (level === this.level) {
console.log(pay * 0.7);
} else {
this.nextChain.getDiscount(pay, level);
}
}

setNextChain(obj) {
this.nextChain = obj;
}
}

export class Vip1{
constructor() {
this.level = 1;
}

getDiscount(pay, level) {
if (level === this.level) {
console.log(pay * 0.9);
} else {
this.nextChain.getDiscount(pay, level);
}
}

setNextChain(obj) {
this.nextChain = obj;
}
}

函数式例子:

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
(function () {

var order = 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('手机库存不足');
}
}
}

var Chain = function (fn) {
this.fn = fn;
this.successor = null;
};

Chain.prototype.setNextSuccessor = function (successor) {
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);
}
};

var order500 = function (orderType, pay, stock) {
if (orderType === 1 && pay === true) {
console.log('500元定金预购,得到100元优惠券');
} else {
return 'nextSuccessor';
}
};

var order200 = function (orderType, pay, stock) {
if (orderType === 2 && pay === true) {
console.log('200元定金预购,得到50元优惠券');
} else {
return 'nextSuccessor';
}
};

var orderNormal = function (orderType, pay, stock) {
if (stock > 0) {
console.log('普通购买,无优惠券');
} else {
console.log('手机库存不足');
}
};

var init = function () {
order(1, true, 500);
var chainOrder500 = new Chain(order500);
var chainOrder200 = new Chain(order200);
var chainOrderNomal = new Chain(orderNormal);

chainOrder500.setNextSuccessor(chainOrder200);
chainOrder200.setNextSuccessor(chainOrderNomal);
chainOrder500.passRequest(1, false, 100);
};
init();
})();