The previous two chapters covered common creative design patterns. This chapter covers a behavioral design pattern
define
Define a set of algorithms, encapsulate them, and make them interchangeable
intentions
Solve complex and difficult to maintain problems caused by using too many if else in many similar scenarios
Example: company performance appraisal and year-end bonus
class Kpi { constructor(grade, base) { //1. Bonus () {if (this.grade === 'D') {return 'Congratulations! If (this.grade === 'C') {return this.base * 2} if (this.grade === 'B') {return this.base * 4 //4 times salary } if (this.grade === 'A') {return this.base * 6 //6 times salary}}Copy the code
This makes it very easy for corporate accountants to calculate everyone’s year-end bonus,
For example, Xiao Wang has a B grade and a base salary of 10000
const wang = new Kpi('B', 10000)
wang.bounds() // 40000
Copy the code
This is not a strategy mode, there is no problem with the function, but it looks like the foot-binding is smelly and long, each time it is added to the inside, this method will get longer and longer.
This is just a simple example, if you judge the keyboard keys that can not judge the 108 keys !!!!
Now let’s use the strategy mode to transform
class Kpi { static grade constructor(grade, base) { //1. Bonus () {return {A: this.isa, B: this.isb, C: this.isc, D: this.isD, } [this.grade] }, isA() { return this.base * 6 } isB() {... } isC() {... } isD() {... }}Copy the code
The structure feels much clearer, and it will be handy if additional levels are added later, without blowing up the Bonus method.
A similar example is front-end form validation
class Rule {
// Verify id
isCardNumber(value) {
const rel = /^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$/
return rel.test(value)
}
isMobile(value){... }// If you want to provide an error message, you can write this
async isEmpty(value, err) {
if( value.length< 1) {
alert(err)
return false}}}Copy the code
We can add methods to the project as needed. If we want to make chained calls or synchronous calls, for example, we can add async before the validation method as isEmpty
// Here is an example
async function submit() {
const myRule = new Rule()
await myRule.isEmpty(this.name, 'Name can't be empty.')
await myRule.isMobile(this.phone)
}
Copy the code
The last whisper
Never give up looking for a third option
We write code, too, always wondering if there is a better solution, and gradually write maintainable code