设计模式之策略模式实践

开发过程中,经常会遇到一些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');
}

至此结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值