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设计模式与开发实践》学习 装饰者 模式 #33

Open
lizhongzhen11 opened this issue Aug 22, 2019 · 0 comments
Labels
设计模式 设计模式

Comments

@lizhongzhen11
Copy link
Owner

lizhongzhen11 commented Aug 22, 2019

理论

给对象动态地增加职责的方式称为装饰者模式

业务中的应用

我认为最佳实践就是表单校验。

最一开始,我这样写表单校验:

// 伪代码
if (条件) {
  console.log('不符合条件。。。')
  return false
}
if (条件) {
  console.log('不符合条件。。。')
  return false
}
...
ajax() // 提交

后来随着业务写多了,慢慢有点代码审美了,这种将校验和保存提交请求写在一个函数内部,简直垃圾的一笔!!!

一旦校验增加、变动就要去改内部代码,而且明显违反了单一职责原则。

我渐渐的,会将校验和提交分成两个函数来写了:

// 伪代码
validate () {
  if (条件) {
    console.log('不符合条件。。。')
    return false
  }
  ...
  return true
}
submit () {
  if (!validate()) {
     return
  }
  ajax()
}

但是,碰到复杂表单/校验较多的表单,validate函数内部依然会有一大堆if...else代码,然后可能这个函数达到数十行,还是十分垃圾,这里面可以结合之前学到的策略模式进行优化。

以前我只做到这一步,然后就没啥更好的想法了。但是,看书发现,还可以继续使用装饰者模式进行优化。

// 伪代码
Function.prototype.before = function (beforeFn) {
  let self = this
  return function () {
    if (beforeFn.apply(this, arguments)) {
      return self.apply(this, arguments)
    }
    return 
  }
}
function validate () {
  if (条件) {
    console.log('不符合条件。。。')
    return false
  }
  ...
  return true
}
function submit () {
  ajax()
}
submit = submit.before(validate)

不污染原型的写法:

function before (func, beforeFunc) {
  return function () {
    if (beforeFunc.apply(this, arguments)) {
      retrurn func.apply(this, arguments)
    }
    return
  }
}
let res = before(submit, validate)
res()
@lizhongzhen11 lizhongzhen11 added the 设计模式 设计模式 label Aug 22, 2019
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