【java_设计模式】策略模式

本文深入讲解策略模式在促销活动中的应用,通过实例演示如何利用策略模式替代冗长的ifelse判断,实现策略的灵活切换。文章详细介绍了策略模式的实现方式,包括策略工厂的构建、策略接口的定义以及具体策略的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习路径: https://coding.imooc.com/class/270.html

  • 前言
    策略模式主要用于减少大量if else代码,在维护不同策略的时候有明显的优势。策略模式往往和工厂模式,享元模式,状态模式一起使用。
  • 应用场景
public static void main(String[] args) {
        // 应用层传入一个key
        String promotionKey = "MANJIAN";
        // new促销活动 -> new促销活动的策略工厂
        PromotionActivity promotionActivity = new PromotionActivity(
                // 促销活动策略工厂,根据key【生成】对应的策略
                PromotionStrategyFactory.getPromotionStrategy(promotionKey)
        );
        // 促销活动【执行】对应的策略
        promotionActivity.executeStrategy();
    }
  • 实现
public class PromotionStrategyFactory {
    // 避免重复创建策略对象,使用Map来共享已经创建好的策略对象
    private static Map<String, PromotionStrategy> PROMOTION_STRATEGY_MAP = new HashMap<>();
    // 避免空指针异常,返回一个非空对象
    private static final PromotionStrategy NON_PROMOTION = new EmptyPromotionStrategy();
    /**
     *  接口里的成员变量默认就是final的,除此之外还可以使用枚举类
     */
    private interface PromotionKey{
        String LIJIAN = "LIJIAN";
        String FANXIAN = "FANXIAN";
        String MANJIAN = "MANJIAN";
    }
    static {
        PROMOTION_STRATEGY_MAP.put(PromotionKey.LIJIAN,new LiJianPromotionStrategy());
        PROMOTION_STRATEGY_MAP.put(PromotionKey.FANXIAN,new LiJianPromotionStrategy());
        PROMOTION_STRATEGY_MAP.put(PromotionKey.MANJIAN,new LiJianPromotionStrategy());
    }

    /**
     * 工厂模式里封装了策略模式,把策略的具体实现类用常量封装
     * @param key
     * @return
     */
    public static PromotionStrategy getPromotionStrategy(String key){
        PromotionStrategy promotionStrategy = PROMOTION_STRATEGY_MAP.get(key);
        return promotionStrategy == null ? NON_PROMOTION : promotionStrategy;
    }
}
/**
 * 策略的标准
 */
public interface PromotionStrategy {
    void doPromotion();
}
public class EmptyPromotionStrategy implements PromotionStrategy {
    @Override
    public void doPromotion() {
        System.out.println("无对应促销活动");
    }
}
public class FanXianPromotionStrategy implements PromotionStrategy {
    @Override
    public void doPromotion() {
        System.out.println("返现促销,业务逻辑。。。");
    }
}
public class ManJianPromotionStrategy implements PromotionStrategy{
    @Override
    public void doPromotion() {
        System.out.println("满减促销,业务逻辑。。。");
    }
}

  • 总结
    策略模式简化了许多if else代码,用key来指定具体策略,对应用层较为友好。如果需要新的策略,只用新增一个PromotionStrategy的实现类即可。但是配合工厂模式的应用,需要修改工厂内的代码新增一个Map中的元素,这里还是可以进行优化的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值