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