项目中很多if-else,看着很难受,难以理解,一分钟教会你最简单解决多个if-else的方法

1 篇文章 0 订阅
1 篇文章 0 订阅

1、定义一个map,可以根据相应的key执行相应的方法。

private Map<ComponentType, Function<SAMSearchParam, List<ComponentSource>>> getComponentSourceDispatcher = new HashMap<>();

    @PostConstruct
    public void getComponentSourceDispatcherInit() {
        getComponentSourceDispatcher.put(ComponentType.job, samSearchParam -> {return null;});
        getComponentSourceDispatcher.put(ComponentType.company, samSearchParam -> {return null;});
    }

    public List<ComponentSource> getComponentSourceSuper(SAMSearchParam samSearchParam) {
        Function<SAMSearchParam, List<ComponentSource>> result = getComponentSourceDispatcher.get(samSearchParam);
        return Optional.ofNullable(result).map(res->res.apply(samSearchParam))
                .orElseGet(Collections::emptyList);
    }

2、使用策略加工厂模式,区分你不同的业务逻辑,把不同的业务代码放到不同的类中去。

/**
 * 定义一个接口
 **/
public interface JobRecoService {
    List<RecommendJob> getRecoJobList(int userId, int jobClass);
}
/**
 * 定义若干个继承,继承接口,分别实现的不同的业务逻辑
 **/
@Service
public class RecoByDeliveryRecord implements JobRecoService {
    @Override
    public List<RecommendJob> getRecoJobList(int userId, int jobClass) {
        return positionIdList;
    }
    @PostConstruct
    public void afterPropertiesSet() throws Exception {
        JobRecoServiceFactory.register(UserTypeEnum.DELIVERYRECORD.getUserType(), this);
    }
}
/**
 * 工厂类
 **/
public class JobRecoServiceFactory {
    private static Map<String, JobRecoService> services = new ConcurrentHashMap<>();
    private JobRecoServiceFactory() {
    }
    public static JobRecoService getJobRecoServiceByType(String userType) {
        return services.get(userType);
    }
    public static void register(String userType, JobRecoService jobRecoService) {
        if (StringUtils.isEmpty(userType))
            throw new RuntimeException("userType can't be null");
        services.put(userType, jobRecoService);
    }
}
/**
 * 调用
 **/
public RecommendJobPageRs recoJobList(int userId, int jobClass, int page, int pageSize) throws MicroserviceException {
        /*根据所属的类型,获取该用户类型下推荐的相关代码*/
        JobRecoService jobRecoService = JobRecoServiceFactory.getJobRecoServiceByType(userType);
        List<RecommendJob> recommendJobList = jobRecoService.getRecoJobList(userId, jobClass);
        return null;
}

3、职责链

/**
 * 重构前
 **/
public void handle(request) {
    if (handlerA.canHandle(request)) {
        handlerA.handleRequest(request);
    } else if (handlerB.canHandle(request)) {
        handlerB.handleRequest(request);
    } else if (handlerC.canHandle(request)) {
        handlerC.handleRequest(request);
    }
}
/**
 * 重构后
 **/
public void handle(request) {
  handlerA.handleRequest(request);
}

public abstract class Handler {
  protected Handler next;
  public abstract void handleRequest(Request request);
  public void setNext(Handler next) { this.next = next; }
}

public class HandlerA extends Handler {
  public void handleRequest(Request request) {
    if (canHandle(request)) doHandle(request);
    else if (next != null) next.handleRequest(request);
  }
}

4、状态机模式

状态机模式是在处理长业务过程中,常用的代码结构。这里有一个简单的状态机系统。
系统的工作原理如下:

  1. 系统的初始状态为init state。在该状态下,用户可以通过http接口下发一个事件(日出事件),这时状态就会变迁为plow state,在这个状态下用户可以下发三种事件:下雨事件(rain)、耕作事件(plow)和灾害事件(fatality)。如果下发plow事件,该状态下就会处于耕作中(isPlowing = true;),如果在耕作中,收到下雨事件,则状态会迁移到收获状态(harvest state);如果没有在耕作中(isPlowing = false;),收到了灾害事件(fatality),则状态会迁移到end state。
    在这里插入图片描述
  2. 下面是代码:
package com.test.model;
/**
 * 定义枚举用来表示状态的切换
 */
public enum StateEnum {

    INIT("init",1),

    PLOW("plowing",2),

    HARVEST("harvest",3),

    END("end",4)

    ;

    private String name;
    private int value;

    public String getName()
    {
        return name;
    }

    StateEnum(String name, int value) {
        this.name = name;
        this.value = value;
    }
}

package com.test.state;

import com.test.model.OrchardEvent;
import com.test.statemachine.StateMachine;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * 定义抽象类,切换状态和执行相应的事件
 */
public abstract class StateBase {

    private StateMachine stateMachine = null;

    public abstract void handleEvent(OrchardEvent event);

    public void setStateMachine(StateMachine stateMachine)
    {
        this.stateMachine = stateMachine;
    }

    public StateMachine getStateMachine()
    {
        return stateMachine;
    }
}

package com.test.state;


import com.test.model.OrchardEvent;
import com.test.model.StateEnum;
import com.test.statemachine.StateMachine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 继承抽象类,并实现相应的方法
 */
public class PlowState extends StateBase {

    boolean isPlowing = false;

    public PlowState(StateMachine stateMachine)
    {
        setStateMachine(stateMachine);
    }

    @Override
    public void handleEvent(OrchardEvent event) {

        switch (event)
        {
            case PLOW:
                isPlowing = true;
                break;
            case RAIN:
                if(isPlowing){
                    getStateMachine().changeStateTo(StateEnum.HARVEST);
                }
                break;
            case FATALITY:
                if(!isPlowing){
                    getStateMachine().changeStateTo(StateEnum.END);
                }
                break;
            case SUNRISE:
                getStateMachine().changeStateTo(StateEnum.PLOW);
                break;
            default:
        }

    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值