策略模式粗浅应用
1、策略集中管理(耦合高): 适合单一功能场景的维护
function Strategy(row) {
// 配置策略,映射业务 let rules = { a: fna, b: fnb, c: fnc }, // 配置参数域,如果参数域不一致 fields = { a: 'a', b: 'a,b' }, code = row.code, field = fields[code], action = rules[code], args = [row]; // 参数转成数组形式 if (field) { let keys = field.split(','); args = keys.map(function(key) { return row[key]; }) } if (action) action.apply(null, args); }
2、动态策略模式(低耦合):适合公共组件或逻辑
/** rules: code: 策略标识 action: 策略响应 fields: 策略参数域 registor: 注册策略 run: 执行策略 **/ let Strategy = { rules: {}, registor(rule) { this.rules[rule.code] = rule; }, run(row) { let rule = this.rules[row.code]; if (rule) { let field = rule.field, args = [row]; if (field) { let fields = field.split(','); args = fields.map(function(key) { return row[key]; }); } console.log('args: ', JSON.stringify(args)) rule.action.apply(null, args); } } }
假定的业务逻辑:
function fna(a) { console.log(a) } function fnb(a, b) { console.log(a, b) } function fnc({a, b, c}) { console.log(a, b, c) }
// 测试 Strategy.registor({ code: 'a', action: fna, field: 'a' }); Strategy.registor({ code: 'b', action: fnb, field: 'a,b' }); Strategy.registor({ code: 'c', action: fnc }); let row = { a: 'A', b: 'B', c: 'C', d: 'D', e: 'E' }; row.code = 'a'; Strategy.run(row); row.code = 'b'; Strategy.run(row); row.code = 'c'; Strategy.run(row);