3
我發現我使用以下模式,當我有一個已知的執行路徑之間的幾個條件。我將在一個Map中定義我的測試用例(在本例中是一個POJO),並使用這些條件來進行密鑰查找。我通常使用術語predicate
。以下代碼模式是否有標準名稱?
這個模式是否有標準名稱,如果有的話,它的使用歷史或上下文是什麼?
var predicates = {
negateRegexp: function (value, operator) {
return !operator.regex.test(value);
},
negateOperand: function (value, operator) {
return value !== operator.operand;
},
affirmRegexp: function (value, operator) {
return operator.regex.test(value);
},
affirmOperand: function (value, operator) {
return value === operator.operand;
}
};
var predicateKey = (operator.prefix === '!' ? 'negate' : 'affirm') +
(operator.regexp ? 'Regexp' : 'Operand');
var testResult = predicates[predicateKey](value, operator);
if (testResult) {
doSomethingWith(value);
}
我使用的JavaScript的例子,因爲這是我平時的工作中,但我敢肯定,我已經看到了其他語言的這種模式(即使OOP類型的那些如Java)
[Wikipedia/Strategy Pattern](https://en.wikipedia.org/wiki/Strategy_pattern) – no1xsyzy