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 (条件) { 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代码,然后可能这个函数达到数十行,还是十分垃圾,这里面可以结合之前学到的策略模式进行优化。
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()
The text was updated successfully, but these errors were encountered:
No branches or pull requests
理论
给对象动态地增加职责的方式称为装饰者模式
业务中的应用
我认为最佳实践就是表单校验。
最一开始,我这样写表单校验:
后来随着业务写多了,慢慢有点代码审美了,这种将校验和保存提交请求写在一个函数内部,简直垃圾的一笔!!!
一旦校验增加、变动就要去改内部代码,而且明显违反了单一职责原则。
我渐渐的,会将校验和提交分成两个函数来写了:
但是,碰到复杂表单/校验较多的表单,
validate
函数内部依然会有一大堆if...else
代码,然后可能这个函数达到数十行,还是十分垃圾,这里面可以结合之前学到的策略模式进行优化。以前我只做到这一步,然后就没啥更好的想法了。但是,看书发现,还可以继续使用装饰者模式进行优化。
不污染原型的写法:
The text was updated successfully, but these errors were encountered: