Skip to content
New issue

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

JavaScript设计模式(十):职责链模式 #32

Open
yangrenmu opened this issue Sep 22, 2020 · 0 comments
Open

JavaScript设计模式(十):职责链模式 #32

yangrenmu opened this issue Sep 22, 2020 · 0 comments
Labels

Comments

@yangrenmu
Copy link
Owner

定义

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

跟策略模式有点像,感觉像ifswitch 的区别。

实现

假如有这样一个场景:商场打折,支付过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) // 普通购买, 无优惠券

小结

与策略模式有点相似,感觉两者的主要区别在于程序中有没有存在链的关系。

@yangrenmu yangrenmu added the mode label Sep 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant