开发过程中,经常会遇到一些switch/case 之类的处理逻辑,当case 的分支比较多时,尤其是业务逻辑处理较为繁琐;这时,就可以通过策略模式来进行解耦处理。
如下是实例
handlerContext.js
// handlerContext 通过策略模式,解耦一些业务逻辑场景
const Context = function () {
this.registerFuns = {};
};
Context.prototype.get = function (key) {
return this.registerFuns[key];
};
Context.prototype.register = function (key, fun) {
this.registerFuns[key] = fun;
};
Context.prototype.bind = function (requireContext) {
const handlers = requireContext;
const reg = /\.\/(.*).js$/;
handlers.keys().forEach(key => {
if (reg.test(key)) {
this.register(RegExp.$1, handlers(key).default || handlers(key));
}
});
};
Context.prototype.bindModule = function (module) {
Object.keys(module).forEach(key => {
if (typeof module[key] === 'function') { this.register(key, module[key]); }
});
};
Context.prototype.process = function (handlerKey, ...rest) {
try {
const fn = this.get(handlerKey);
if (!fn) return true;
return fn && fn.apply({}, rest);
} catch (err) {
console.error(`处理 ${handlerKey} 节点出现错误`, err);
throw err;
}
};
const ContextMap = {};
export function createInstance (key) {
if (ContextMap[key] && ContextMap[key] instanceof Context) return ContextMap[key];
const handlerContext = new Context();
ContextMap[key] = handlerContext;
return handlerContext;
}
export function getInstance (key) {
if (ContextMap[key] && ContextMap[key] instanceof Context) return ContextMap[key];
}
export function destoryInstance (key) {
if (ContextMap[key] && ContextMap[key] instanceof Context) delete ContextMap[key];
}
使用示例
改造前代码:
function (type, name) {
...
switch(type) {
case 'button': {
// do something.
console.log('button');
break;
}
case 'select': {
// do something.
console.log('select');
break
}
...
}
...
}
改造代码后:
import { createInstance } from 'utils/handlerContext';
const filterHandlerContext = new createInstance('filterHandlerContext');
filterHandlerContext.regist('button', name => {
// do something.
console.log('button');
return;
});
filterHandlerContext.regist('select', name => {
// do something.
console.log('select');
return;
});
function (type, name) {
...
filterHandlerContext.process(type, name);
...
}
其他示例
const handleContext = createInstance('tansferInstance');
handleContext.bind(require.context('./handler', false, /\.js$/));
// 调用
handleContext.process(type, node, options);
// handler 目录
// button.js
export default function handler(node, options) {
// do something.
console.log('button');
}
// select.js
export default function handler(node, options) {
// do something.
console.log('select');
}
至此结束。