This is the 11th day of my participation in Gwen Challenge
The strategy pattern
The strategy pattern refers to defining a set of algorithms, encapsulating them one by one, and making them interchangeable. In our daily development, we can use policy patterns to encapsulate the business rules of certain methods as long as they point to the same goals and can be used interchangeably.
We’ve seen a lot of code like this before, with the longest being for form validation:
onsubmit = (formData) = > {
let { name, pwd, email } = formData;
if(name.value === ' ') {
alert('User name cannot be empty');
return false;
}
if(pwd.value.length < 5) {
alert('Password must not be less than 5 digits');
return false;
}
if(emailRegexp.test(email.value)) {
alert('Please fill in the correct email address');
return false; }}Copy the code
If more of the form values, we need to check every one, we need to write a lot of the if condition, form a form is submitted more than half are in the form of a check, actually we can put all of these abstract away, written in a unified way, let them receive different parameters, according to the way we need to return it. Among them is the idea of strategic patterns.
Start by creating a validation method, validataFunc
const validataFunc = () = > {
let validator = new Validator();
validator.add(name, 'isNonEmpty'.'User name cannot be empty');
validator.add(pwd, 'minLen:5'.'Password must not be less than 5 digits');
validator.add(email, 'isEmail'.'Please fill in the correct email address');
return validator.result();
}
Copy the code
We added a validation to the Validator to validate all form data in a custom way.
// Combine the previous validations into an object
const strategies = {
isNonEmpty: (value, errmsg) = > {
if(value === ' ') {
returnerrmsg; }},minLen: (value, len, errmsg) = > {
if(value.length < len) {
returnerrmsg; }},isEmail: (value, errmsg) = > {
if(emailRegexp.test(value)) {
returnerrmsg; }}}// Match the corresponding Validator method in the Validator class and return the error message
class Validator {
constructor() {
this.cache = [];
}
add(value, rule, err) {
let ary = rule.split(':');
this.cache.push(() = > {
let strategy = ary.shift();
ary.unshift(value);
ary.push(err);
return strategies[strategy].apply(value, ary);
});
}
result() {
for(let validate of this.cache) {
let msg = validate();
if(msg) {
return msg
}
}
}
}
Copy the code
Like this, we can abstract all the basic form validation into a single form validation class. In this case, we simply need to call validataFunc in the form submission method.
onsubmit = (formData) = > {
let errmsg = validataFunc();
if(errmsg) {
alert(errmsg);
return false;
}
// continue
}
Copy the code
And many verification methods in strategies can be reused, which is very convenient.
At this point, end. salute