首页 > 其他分享 >优化if...else...语句

优化if...else...语句

时间:2023-01-16 17:13:44浏览次数:38  
标签:语句 ... handle void public VipService Override else class

写代码的时候经常遇到这样的场景:根据某个字段值来进行不同的逻辑处理。例如,不同的会员等级在购物时有不同的折扣力度。如果会员的等级很多,那么代码中与之相关的if...elseif...else...会特别长,而且每新增一种等级时需要修改原先的代码。可以用策略模式来优化,消除这种场景下的if...elseif...else...,使代码看起来更优雅。

首先,定义一个接口

/**
 * 会员服务
 */
public interface VipService {
    void handle();
}

然后,定义实现类

/**
 * 白银会员
 */
public class SilverVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("白银");
    }
}

/**
 * 黄金会员
 */
public class GoldVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("黄金");
    }
}

最后,定义一个工厂类,目的是当传入一个会员等级后,返回其对应的处理类

public class VipServiceFactory {
    private static Map<String, VipService> vipMap = new ConcurrentHashMap<>();

    public static void register(String type, VipService service) {
        vipMap.put(type, service);
    }

    public static VipService getService(String type) {
        return vipMap.get(type);
    }
}

为了建立会员等级和与之对应的处理类之间的映射关系,这里通常可以有这么几种处理方式:

方式一:实现类手动注册

可以实现InitializingBean接口,或者在某个方法上加@PostConstruct注解

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * 白银会员
 */
@Component
public class SilverVipService implements VipService, InitializingBean {
    @Override
    public void handle() {
        System.out.println("白银");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        VipServiceFactory.register("silver", this);
    }
}

/**
 * 黄金会员
 */
@Component
public class GoldVipService implements VipService, InitializingBean {
    @Override
    public void handle() {
        System.out.println("黄金");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        VipServiceFactory.register("gold", this);
    }
}

方式二:从Spring容器中直接获取Bean

public interface VipService {
    void handle();
    String getType();
}

/**
 * 白银会员
 */
@Component
public class SilverVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("白银");
    }
    @Override
    public String getType() {
        return "silver";
    }
}

/**
 * 黄金会员
 */
@Component
public class GoldVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("黄金");
    }
    @Override
    public String getType() {
        return "gold";
    }
}

/**
 * 上下文
 */
@Component
public class VipServiceFactory implements ApplicationContextAware {
    private static Map<String, VipService> vipMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, VipService> map = applicationContext.getBeansOfType(VipService.class);
        map.values().forEach(service -> vipMap.put(service.getType(), service));
    }

    public static VipService getService(String type) {
        return vipMap.get(type);
    }
}

/**
 * 测试
 */
@SpringBootTest
class DemoApplicationTests {
    @Test
    void contextLoads() {
        VipServiceFactory.getService("silver").handle();
    }
}

方式三:反射+自定义注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MemberLevel {
    String value();
}

@MemberLevel("silver")
@Component
public class SilverVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("白银");
    }
}

@MemberLevel("gold")
@Component
public class GoldVipService implements VipService {
    @Override
    public void handle() {
        System.out.println("黄金");
    }
}

/**
 * 上下文
 */
@Component
public class VipServiceFactory implements ApplicationContextAware {
    private static Map<String, VipService> vipMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//        Map<String, VipService> map = applicationContext.getBeansOfType(VipService.class);
        Map<String, Object> map = applicationContext.getBeansWithAnnotation(MemberLevel.class);
        for (Object bean : map.values()) {
            if (bean instanceof VipService) {
                String type = bean.getClass().getAnnotation(MemberLevel.class).value();
                vipMap.put(type, (VipService) bean);
            }
        }
    }

    public static VipService getService(String type) {
        return vipMap.get(type);
    }
}

完整示例代码

/**
 * 结算业务种类
 * @Author: ChengJianSheng
 * @Date: 2023/1/16
 */
@Getter
public enum SettlementBusiType {
    RE1011("RE1011", "转贴现"),
    RE4011("RE4011", "买断式贴现"),
    RE4021("RE4021", "回购式贴现"),
    RE4022("RE4022", "回购式贴现赎回");
//    ......

    private String code;
    private String name;

    SettlementBusiType(String code, String name) {
        this.code = code;
        this.name = name;
    }
}


/**
 * 结算处理器
 * @Author: ChengJianSheng
 * @Date: 2023/1/16
 */
public interface SettlementHandler {
    /**
     * 清算
     */
    void handle();

    /**
     * 获取业务种类
     */
    SettlementBusiType getBusiType();
}


/**
 * 转贴现结算处理
 */
@Component
public class RediscountSettlementHandler implements SettlementHandler {
    @Override
    public void handle() {
        System.out.println("转贴现");
    }

    @Override
    public SettlementBusiType getBusiType() {
        return SettlementBusiType.RE1011;
    }
}


/**
 * 买断式贴现结算处理
 */
@Component
public class BuyoutDiscountSettlementHandler implements SettlementHandler {
    @Override
    public void handle() {
        System.out.println("买断式贴现");
    }

    @Override
    public SettlementBusiType getBusiType() {
        return SettlementBusiType.RE4011;
    }
}


/**
 * 默认处理器
 * @Author: ChengJianSheng
 * @Date: 2023/1/16
 */
@Component
public class DefaultSettlementHandler implements /*SettlementHandler,*/ ApplicationContextAware {
    private static Map<SettlementBusiType, SettlementHandler> allHandlerMap = new ConcurrentHashMap<>();

    public static SettlementHandler getHandler(SettlementBusiType busiType) {
        return allHandlerMap.get(busiType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, SettlementHandler> map = applicationContext.getBeansOfType(SettlementHandler.class);
        map.values().forEach(e -> allHandlerMap.put(e.getBusiType(), e));
    }
}


@SpringBootTest
class Demo2023ApplicationTests {
    @Test
    void contextLoads() {
        SettlementHandler handler = DefaultSettlementHandler.getHandler(SettlementBusiType.RE1011);
        if (null != handler) {
            handler.handle();
        }
    }
}

 

标签:语句,...,handle,void,public,VipService,Override,else,class
From: https://www.cnblogs.com/cjsblog/p/17055846.html

相关文章

  • SQL DML语句 知识点
    ALTER用法ALTERTABLE表名ADD列名/索引/主键/外键等;ALTERTABLE表名DROP列名/索引/主键/外键等;ALTERTABLE表名ALTER仅用来改变某列的默认值;ALTERTABLE表名......
  • initial语句
    关键词:initial,always过程结构语句有2种,initial与always语句。它们是行为级建模的2种基本语句。一个模块中可以包含多个initial和always语句,但2种语句不能嵌......
  • 对vc中radio单选按钮进行初始化!...
    Getdlgitem(你要的那个单选的id)->SetCheck(true);//呵呵,以下为我从网上整理的资料,留着有用。调用CButton的成员函数GetCheck返回单选钮的选中状态。该函数的函数原型是in......
  • 循环语句
    目录循环语句while循环简单循环嵌套循环for循环简单循环嵌套循环循环的关键词循环语句while循环简单循环while条件:循环体嵌套循环while条件:while条件:......
  • 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半...
    ----------------------------------------------------------------------------------------------------------------------------------有这样一道题目;    猴子......
  • CentOS7出现dracut:/#...time错误的解决方法
    出现这个错误的原因是:找不到你的设备(启动盘) 网上很多人说ls|grepsdb查找自己的设备然而你的设备可能是sdc开头的所以不准确,建议用一下操作找自己的设备(启动盘)......
  • 遍历数组 [第一个值,第二个值,....最后一个值]的格式显示
    packagecom.fqs.demo;publicclassChongZ{//遍历数组以[第一个值,第二个值,....最后一个值]的格式publicstaticvoidmain(String[]args){int......
  • shell 脚本if语句
    思路:判断/root/test/下是否有14这个文件,如果有.就拷贝到/home目录下例:#!/bin/bashif  [-f/root/test/14]||cp/root/test/14/home  then       echo......
  • for 语句
    for语句是循环语句中的一种。for语句可以使程序在某一个条件下重复执行一段代码。1.基本语法for语句相对于if语句稍微复杂,通常为以下格式:for(初始语句;条件;条件为......
  • JavaScript while 语句
    while语句可以在某个条件表达式为真的前提下,循环执行指定的一段代码,直到那个表达式不为真时结束循环。——MDNwhile语句也是一种循环语句,也称while循环。while循环接......