DAY 2
0
Modern Web

## 今天寫第二種模式:策略模式Strategy!!

``````var calcBonus = function(performance, salary) {
if (performance === 'S') {
return salary * 4;
}
if (performance === 'A') {
return salary * 3;
}
if (performance === 'B') {
return salary * 2;
}
};
console.log(calcBonus('A', 100));
``````

1.太多if-else述句
2.違反開放-封閉原則:若要新增一個等級或是修改規則就要深入calcBonus內部實作

``````//演算法
var strategies = {
'S': function(salary) {
return salary * 4;
},
'A': function(salary) {
return salary * 3;
},
'B': function(salary) {
return salary * 2;
}
};

//使用它
var calcBonus = function(performance, salary) {
return strategies[performance](salary);
};
console.log(calcBonus('S', 100));
``````

``````var \$form = getForm();
\$form.submit(onSubmit);

function onSubmit() {
var form = this;
return false;
}
return false;
}
if (!/^[09]{2}[0-9]{8}\$/.test(form.phoneNumber.value)) {
return false;
}
}

//製作表單畫面(可以忽略)
function getForm() {
var \$form = \$('<form>').appendTo('body').attr('method', 'post');
createLine('手機號碼:', 'phoneNumber').appendTo(\$form);
createButton().appendTo(\$form);
return \$form;

function createButton() {
return \$('<button>').text('submit');
}

function createLine(text, name) {
var \$label = \$('<span>').text(text);
var \$input = \$('<input>').attr('name', name);
return \$('<div>').append(\$label).append(\$input);
}
}
``````

1.if else結構太多。
2.若檢驗的內容須改變，就必須深入onSubmit中去修改。
3.重用性差，表單常常不只一個，每個都要判斷的話就可能會一直複製貼上。

``````var strategies = {
inNotEmpty: function(val, errorMsg) {
if (val === '') {
return errorMsg;
}
},
minLength: function(val, length, errorMsg) {
if (val.length < length) {
return errorMsg;
}
},
isMobileNumber: function(val, errorMsg) {
if (!/^[09]{2}[0-9]{8}\$/.test(val)) {
return errorMsg;
}
}
};
``````

``````function myFormValidator(form) {
var validator = new Validator();
strategy: 'inNotEmpty',
errorMsg: '使用者名稱不為空'
}, {
strategy: 'minLength:6',
errorMsg: '使用者名稱位數不得少於6'
}]);
strategy: 'minLength:6',
errorMsg: '密碼位數不得少於6'
}]);
strategy: 'isMobileNumber',
errorMsg: '手機號碼錯誤'
}]);
var errorMsg = validator.start();
return errorMsg;
}
``````

``````var Validator = function() {
this.cache = [];
};

var self = this;
rules.forEach(function(rule) {
var strategySet = rule.strategy.split(':');
self.cache.push(function() {
var strategyName = strategySet.shift();
strategySet.unshift(item);
strategySet.push(rule.errorMsg);
return strategies[strategyName].apply(self, strategySet);
});
});
};

Validator.prototype.start = function() {
var errorMsg;
this.cache.some(function(validatorFunc) {
errorMsg = validatorFunc();
if (errorMsg) {
return true;
}
});
return errorMsg;
};
``````

``````{
strategy: 'minLength:6',
errorMsg: '密碼位數不得少於6'
}
``````

``````var \$form = getForm();
\$form.submit(onSubmit);

function onSubmit() {
var form = this;
var errorMsg = myFormValidator(form);
if (errorMsg) {
return false;
}
}
``````

``````var \$form = getForm();
\$form.submit(onSubmit);

function onSubmit() {
var form = this;
var errorMsg = myFormValidator(form);
if (errorMsg) {
return false;
}
}
var strategies = {
inNotEmpty: function(val, errorMsg) {
if (val === '') {
return errorMsg;
}
},
minLength: function(val, length, errorMsg) {
if (val.length < length) {
return errorMsg;
}
},
isMobileNumber: function(val, errorMsg) {
if (!/^[09]{2}[0-9]{8}\$/.test(val)) {
return errorMsg;
}
}
};

function myFormValidator(form) {
var validator = new Validator();
strategy: 'inNotEmpty',
errorMsg: '使用者名稱不為空'
}, {
strategy: 'minLength:6',
errorMsg: '使用者名稱位數不得少於6'
}]);
strategy: 'minLength:6',
errorMsg: '密碼位數不得少於6'
}]);
strategy: 'isMobileNumber',
errorMsg: '手機號碼錯誤'
}]);
var errorMsg = validator.start();
return errorMsg;
}

var Validator = function() {
this.cache = [];
};

var self = this;
rules.forEach(function(rule) {
var strategySet = rule.strategy.split(':');
self.cache.push(function() {
var strategyName = strategySet.shift();
strategySet.unshift(item);
strategySet.push(rule.errorMsg);
return strategies[strategyName].apply(self, strategySet);
});
});
};

Validator.prototype.start = function() {
var errorMsg;
this.cache.some(function(validatorFunc) {
errorMsg = validatorFunc();
if (errorMsg) {
return true;
}
});
return errorMsg;
};
``````

1.避免過多重複代碼，若類似的表單要用到這三個規則的直接套用myFormValidator就好。
2.組合彈性高，若有不同規則組合的表單也可以像製作myFormValidator一樣做一個新的檢查規則。
3.易於擴展，若有新的演算法的話只要新增在strategies裡面即可。

### 1 則留言

0

iT邦新手 5 級 ‧ 2019-08-19 18:56:56