设计模式--策略模式的精简用法案例

参考链接: https://www.cnblogs.com/z-qinfeng/p/12314942.html

我遇到的场景是根据不同的type类型,来使用不同的计算积分的方式.

1: 枚举的定义:

public enum NotifyType {


    BREEZE_TYPE_12("纸类",NotifyMechanismInterface.byEmail()),
    BREEZE_TYPE_18("塑料",NotifyMechanismInterface.bySms()),
    BREEZE_TYPE_28("玻璃",NotifyMechanismInterface.byWeChat());



    private String  type;
    private NotifyMechanismInterface notifyMechanism;

    NotifyType(String type, NotifyMechanismInterface notifyMechanism) {
        this.type = type;
        this.notifyMechanism = notifyMechanism;
    }
    
    public String type() {
        return type;
    }
    public NotifyMechanismInterface notifyMechanism() {
        return notifyMechanism;
    }

}

2:接口定义:

public interface NotifyMechanismInterface {

    Double doNotify(Double beforeWeight,Double afterWeight);

    static NotifyMechanismInterface byEmail() {
        return (beforeWeight, afterWeight) -> {
            // todo 业务逻辑

            System.out.println("计算emaile类型的积分数量");

            return   DoubleUtils.sub(afterWeight,beforeWeight);
        };
    }
    /**
     * 使用lambda表达式
     *
     * @return
     */
    static NotifyMechanismInterface bySms() {
        return (beforeWeight, afterWeight) -> {
            // todo 业务逻辑
            System.out.println("计算SMS类型的积分数量");
            return   DoubleUtils.sub(afterWeight,beforeWeight);
        };
    }

    static NotifyMechanismInterface byWeChat() {
        return (beforeWeight, afterWeight) -> {
            // todo 业务逻辑
            System.out.println("计算WeChat类型的积分数量");
            //System.out.println("通过邮件通知:" + msg);
            return   DoubleUtils.sub(afterWeight,beforeWeight);
        };
    }
}

3:枚举类型中的对应绑定关系的建立:

public class NotifyService {

    public Double doNotify(String  type,Double beforeWeight,Double afterWeight) {

          return   NotifyType.valueOf("BREEZE_TYPE_".concat(type)).notifyMechanism().doNotify(beforeWeight,afterWeight);

    }
    
}

4:测试代码:

public class TestEnums {

        @Autowired
        private  NotifyService notifyService;
        public static void main(String[] args){
            NotifyService notifyService = new NotifyService();
            System.out.println("EMAIL类型的计算: "+notifyService.doNotify("12",12D,16D));
            System.out.println("SMS类型的计算: "+notifyService.doNotify("18",12D,17D));
            System.out.println("WECHAT类型的计算: "+notifyService.doNotify("28",12D,18D));

        }

}

这个demo可以直接测试使用;根据自己的业务场景进行修改业务逻辑就可以!!!!!

猜你喜欢

转载自blog.csdn.net/zty1317313805/article/details/108884864