这段代码是采用if-else的方式判断多个不同的条件。
function permission(role){ if(role === "operations"){ getOperationPermission() }else if(role === "admin"){ getAdminPermission() }else if(role === "superAdmin"){ getSuperAdminPermission() }else if(role === "user"){ getUserPermission() } }
用switch优化后为:
function permission(role) { switch (role) { case "operations": { getOperationPermission(); break; } case "admin": { getAdminPermission(); break; } case "superAdmin": { getSuperAdminPermission(); break; } case "user": { getUserPermission(); break; } } }
这种写法虽然使代码清晰了许多,但是依旧不合格,接下来我们看看采用策略模式后的结果:
function permission(role) { const actions = { operations: getOperationPermission, admin: getAdminPermission, superAdmin: getSuperAdminPermission, user: getUserPermission, }; actions[role].call(); }
比起前面两种写法,显然采用策略模式要更加优雅。
我们将策略模式用于修改生产的代码,
如将
switch (active.value) { case 0: getPendingApprovalList(); break; case 1: getApprovedList(); break; case 2: getExpiredList(); break; case 3: getMyOrderList(); break; }
修改成
const queryFuncArr = [ getPendingApprovalList, getApprovedList, getExpiredList, getMyOrderList, ]; queryFuncArr[active.value].call();
既精简了代码又使代码结构清晰。
标签:case,operations,代码,模式,JS,break,role,else,优化 From: https://www.cnblogs.com/luoyihao/p/16710199.html