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

职责链模式 #13

Open
txw2018 opened this issue May 9, 2020 · 0 comments
Open

职责链模式 #13

txw2018 opened this issue May 9, 2020 · 0 comments

Comments

@txw2018
Copy link
Owner

txw2018 commented May 9, 2020

定义: 为解除请求的发送者和接收者之间耦合,而使多个对象都有机会处理这个请求。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它

下面模拟购物车提交订单流程

const UI = {
  Alert(options) {
    const msg = options.msg || '您确定吗'
    return new Promise((resolve, reject) => {
      var r = confirm(msg)
      if (r) {
        resolve(true)
      } else {
        reject(false)
      }
    })
  }
}

const validateHandler = {
  validateAddress() {
    if (true) {
      UI.Alert({
        msg: "您确定地址正确吗"
      })
      .then(() => {
        console.log(1111)
        this.next()
      })
      .catch(err => {
      })
    }
    return false
  },
  validateMoney() {
    if (true) {
      UI.Alert({
        msg: "您确定继续支付吗"
      })
      .then(() => {
        console.log(2222)
        this.next()
      })
      .catch(err => {
      })

    }
    return false
  },
  validateCoupon() {
    if (true) {
      console.log(3333)
      return true
    }
    return false
  }
}
class Chain {
  constructor(fn) {
    this.fn = fn
    this.sucessor = null
  }
  setNext(fnc) {
    this.sucessor = fnc
    return fnc
  }
  next() {
    this.sucessor.run.apply(this.sucessor, arguments)
  }
  run() {
    const result = this.fn.apply(this, arguments)
    if (result) {
      this.next()
    }
  }
}
const validateObj = {}

const validateArr = Object.keys(validateHandler)


for (const fnc of validateArr) { // 循环执行验证方法
  validateObj[fnc + 'Chain'] = new Chain(validateHandler[fnc])
}

const {
  validateAddressChain,
  validateMoneyChain,
  validateCouponChain
} = validateObj


validateAddressChain
  .setNext(validateMoneyChain)
  .setNext(validateCouponChain)

validateAddressChain.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant