We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
跟策略模式有点像,感觉像if 跟 switch 的区别。
if
switch
假如有这样一个场景:商场打折,支付过500元定金的用户,会有100元的优惠券。支付200元定金的用户可以收到50元优惠券。没有支付定金的用户,普通购买。 先看看一般的代码:
// orderType: 订单类型,1 是500元定金用户,2 是200元定金用户,3 是普通购买 // pay: 是否支付了定金 // stock: 表示普通购买时的库存量 const 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('库存不够, 无法购买') } } } order(3, true, 500) // 普通购买, 无优惠券
现在我们用职责链模式来重构下:
const order500 = function (orderType, pay, stock) { if (orderType === 1 && pay === true) { console.log('500 元定金预购, 得到 100 元优惠券') } else { order200(orderType, pay, stock) } } const order200 = function (orderType, pay, stock) { if (orderType === 2 && pay === true) { console.log('200 元定金预购, 得到 50 元优惠券') } else { orderCommon(orderType, pay, stock) } } const orderCommon = function (orderType, pay, stock) { if (orderType === 3 && stock > 0) { console.log('普通购买, 无优惠券') } else { console.log('库存不够, 无法购买') } } order500(3, true, 500) // 普通购买, 无优惠券
与策略模式有点相似,感觉两者的主要区别在于程序中有没有存在链的关系。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
定义
跟策略模式有点像,感觉像
if
跟switch
的区别。实现
假如有这样一个场景:商场打折,支付过500元定金的用户,会有100元的优惠券。支付200元定金的用户可以收到50元优惠券。没有支付定金的用户,普通购买。
先看看一般的代码:
现在我们用职责链模式来重构下:
小结
与策略模式有点相似,感觉两者的主要区别在于程序中有没有存在链的关系。
The text was updated successfully, but these errors were encountered: