策略模式
const PerformanceS = function() {};
performanceS.prototype.calculate = function(salary) {
return salary * 4;
};
const PerformanceA = function() {};
performanceA.prototype.calculate = function(salary) {
return salary * 3;
};
const PerformanceB = function() {};
performanceB.prototype.calculate = function(salary) {
return salary * 2;
};
const Bonus = function() {
this.salary = null;
this.strategy = null;
};
Bonus.prototype.setSalary = function(salary) {
this.salary = salary;
};
Bonus.prototype.setStrategy = function(strategy) {
this.strategy = strategy;
};
Bonus.prototype.getBonus = function() {
return this.strategy.calculate(this.salary);
};
let bonus = new Bonus();
bonus.setSalary(10000);
bonus.setStrategy(new PerformanceS());
console.log(bonus.getBonus());
const Strategies = {
S: function(salary) {
return salary * 4;
},
A: function(salary) {
return salary * 3;
},
B: function(salary) {
return salary * 2;
}
};
function calculateBonus(level, salary) {
return Strategies[level](salary);
}
console.log(calculateBonus('S', 20000));
const PointToPoint = {
linear: function(t, b, c, d) {
return c * t / d + b;
},
easeIn: function(t, b, c, d) {
return c * (t /= d) * t + b;
},
strongEaseIn: function(t, b, c, d) {
return c * (t /= d) * t * t * t * t + b;
},
strongEaseOut: function(t, b, c, d) {
return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
},
sineaseIn: function(t, b, c, d) {
return c * (t /= d) * t * t + b;
},
sineaseOut: function(t, b, c, d) {
return c * ((t = t / d - 1) * t * t + 1) + b;
}
};
const Rules = {
isNonEmpty: function(value, errorMsg) {
if(value === '') {
return errorMsg;
}
},
minLength: function(value, length, errorMsg) {
if(value.length < length) {
return errorMsg;
}
},
isMobileNumber: function(value, errorMsg) {
if(!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
return errorMsg;
}
}
};
function Validator() {
this.cache = [];
}
Validator.prototype.add = function(dom, rule, errorMsg) {
let ary = rule.split(':');
this.cache.push(function() {
let strategy = ary.shift();
ary.unshift(dom.value);
ary.push(errorMsg);
return Rules[strategy].apply(dom, ary)
});
};
Validator.prototype.start = function() {
for(let i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
let msg = validatorFunc();
if(msg) {
return msg;
}
}
};
function validatorFunc() {
let validtor = new Validator();
validator.add(registerForm.userName, 'isNonEmpty', '用户名不能少于6位');
validator.add(registerForm.password, 'minLength:8', '密码不能少于8位');
validator.add(registerForm.phoneNumber, 'isMobileNumber', '手机号码格式不对');
let errorMsg = validator.start();
return errorMsg;
};
const registerForm = document.querySelector('#registerForm');
registerForm.onsubmit = function() {
let errorMsg = validatorFunc();
if(errorMsg) {
alert(errorMsg);
return false;
}
};