枚举+Lamda+静态方法策略 干掉if else

1 需求导致if else很多

用户关于订单的操作种类很多,需要记录下来,并发送信息给用户(信息要根据操作类型动态匹配)

2 解决方法

2.1 方案1 :通过if else 判断

好处

  • 一开始容易些
缺点
  • if else过多导致维护难,如果增加逻辑,则需要修改这个方 法,危险性高,而且不符合开闭原则

2.2 方案2 常规 策略模式

好处

  • 代码解构,易扩展

缺点

  • 一个if,一个实现策略类,导致策略类过多(当然此处也可以使用lambda,并将策略封装成方法)
  • 只是将if 的逻辑写成了策略,但是if else并未减少

2.3 方案3 枚举+Lamda+静态方法策略

优点

  • 不用if else
  • 使用策略,代码解耦,易扩展

3 枚举+Lamda+静态方法策略 方案举例

使用 1的需求

3.1 定义策略接口

/**
 * 根据订单返回不同的信息
 */
@FunctionalInterface
public interface MsgInterface {

    String getMsg(Integer orderId);
}

3.2 定义策略静态方法


/**
 * 消息策略类
 *
 * @Auther: ZhangSuchao
 * @Date: 2020/8/10 22:04
 */
public class MsgStrategy {

    /**
     * 创建订单策略
     *
     * @param orderId
     * @return
     */
    public static String createOrder(Integer orderId) {
        // TODO: 2020/8/10  做一些业务逻辑,封装msg信息

        return "用户创建了一个订单" + orderId;
    }

    /**
     * 取消订单策略
     *
     * @param orderId
     * @return
     */
    public static String cancleOrder(Integer orderId) {

        return "用户取消了一个订单" + orderId;
    }
}

3.3 枚举+Lamda

package com.draymond.mp.mp;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: ZhangSuchao
 * @Date: 2020/8/10 21:21
 */
public enum OperatorKind {

    // 创建订单
    CREATE_ORDER(1, MsgStrategy::createOrder),
    // 取消订单
    CANCLE_ORDER(2, MsgStrategy::cancleOrder),

    ;

    private final Integer operatorKind;
    private final MsgInterface msgInterface;

    OperatorKind(Integer symbol, MsgInterface msgInterface) {
        this.operatorKind = symbol;
        this.msgInterface = msgInterface;
    }

    public static Map<Integer, OperatorKind> map = new HashMap<>();

    static {
        OperatorKind[] values = values();
        for (OperatorKind operatorKind : values) {
            map.put(operatorKind.operatorKind, operatorKind);
        }
    }

    public static OperatorKind getByCode(Integer code) {
        return map.get(code);
    }

    /**
     * 执行策略
     *
     * @param orderId
     * @return
     */
    public String apply(Integer orderId) {
        return msgInterface.getMsg(orderId);
    }


}

3.4 测试及打印结果

    public static void main(String[] args) {

        int create = 1;
        int cancle = 2;
        int order = 2;

        String createMsg = OperatorKind.getByCode(create).apply(order);
        String cancleMsg = OperatorKind.getByCode(cancle).apply(order);

        System.out.println(createMsg); // 用户创建了一个订单2
        System.out.println(cancleMsg); // 用户取消了一个订单2
    }

备注

  • 如果需要修改策略,直接修改策略类的单个方法
  • 如果需要增加逻辑判断 ,可以直接增加枚举类种的实例,增加策略

猜你喜欢

转载自blog.csdn.net/Draymond_feng/article/details/107924465