首页 > 其他分享 >JS使用策略模式优化条件选择结构

JS使用策略模式优化条件选择结构

时间:2022-09-20 10:45:43浏览次数:59  
标签:case operations 代码 模式 JS break role else 优化

这段代码是采用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

相关文章

  • SpringBoot Xml转Json对象
    一、导入需要的依赖<dependency><groupId>maven</groupId><artifactId>dom4j</artifactId><version>1.7-20060614</version></dependency>二、xml......
  • FastJson 的一些配置
    主要提到:关闭循环引用的配置"$ref":"$.data[0].detail.wmsInboundorder.details[1]"如下:importcom.alibaba.fastjson.serializer.SerializeConfig;importcom.alib......
  • node.js 使用教程-3.gulp-file-include 详细教程
    前言gulp-file-include是gulp插件,它提供了一个include方法让我们可以像后端模板那样把公共部分的页面导入进来,实现html复用。环境准备gulp-file-include是gulp的......
  • 聊聊如何利用管道模式来进行业务编排(下篇)
    前言上篇文章我们介绍利用管道模式来进行业务编排的2种实现方式。本文又来介绍其他实现方式实现方式方式一:利用springboot自动装配1、新建管道实体@Data@AllArgsCo......
  • 【设计模式】Java设计模式 - 模板模式
    Java设计模式-模板模式......
  • 设计模式在业务系统中的应用
      本文的重点在于说明工作中所使用的设计模式,为了能够更好的理解设计模式,首先简单介绍一下业务场景。使用设计模式,可以简化代码、提高扩展性、可维护性和复用性。有哪......
  • Java:Json与List对象的相互转换
    谷歌的Gson.jar://list转换为jsonGsongson=newGson();List<Person>persons=newArrayList<Person>();Stringstr=gson.toJson(persons);//json转换为listGs......
  • Delphi中TWebBrowser中注入Js
    最近帮朋友做一个软件,其中要自动化某网页中的操作,最简的操作是调用自己写的代码。代码如下:procedureTForm1.Button2Click(Sender:TObject);var i:integer; h:IHTML......
  • ASP.NET Core 读取配置文件JSON 数据、数组
    配置访问接口publicIConfiguration_Config;public类名(IConfigurationConfig){_Config=Config;}配置文件数据示例{"AllowedHosts":"*","......
  • Redis集群:Sentinel哨兵模式
    Redis集群:Sentinel哨兵模式(详细图解)(biancheng.net)在Redis主从复制模式中,因为系统不具备自动恢复的功能,所以当主服务器(master)宕机后,需要手动把一台从服务器(slave)切......