JAVA架构师之路十五:设计模式之策略模式

本文探讨了设计模式中的策略模式,解释了其定义、适用场景、优缺点,并通过实例——优惠券和支付案例,展示了策略模式在实际问题中的应用。文章旨在帮助读者更好地理解和运用策略模式,提升软件设计能力。
摘要由CSDN通过智能技术生成

JAVA架构师之路十四:设计模式之模板模式

人生的游戏不在于拿了一副好牌,而在于怎样去打好坏牌,世上没有常胜将军,勇于超越自我者才能得到最后的奖杯。

1. 策略模式

定义

策略模式又叫政策模式,它是将定义的算法家族,分别封装起来,让它们之间可以互相替换,从而让算法的变化不会影响到使用算法的用户。

可以避免多重分支的if 。。。。else 和switch语句。

属于行为型模式

适用场景

假如系统中有很多的类,而他们的区别仅仅在于他们的行为不同。

一个系统需要动态地在几种算法中选择一种

需要屏蔽算法规则

优点

策略模式符合开闭原则

避免使用多出个的条件转移语句,如if … else 、switch语句

使用策略模式可以提高算法的保密性和安全性。

缺点

客户端必须要知道所有的策略,并且自己决定执行使用哪一个策略类

代码中会产生非常多的策略类,增加维护难度

2. 优惠券案例

网购中有很多优惠策略,那么这种场景非常适合策略模式

public interface IPromotionStrategy {
   

    void doPromotion();
}
public class CashbackStrategy implements IPromotionStrategy {
   
    public void doPromotion() {
   
        System.out.println("返现,直接打款到支付宝账号");
    }
}
public class CouponStrategy implements IPromotionStrategy {
   
    public void doPromotion() {
   
        System.out.println("使用优惠券抵扣");
    }
}
public class EmptyStrategy implements IPromotionStrategy {
   
    public void doPromotion() {
   
        System.out.println("无优惠");
    }
}
public class GroupBuyStrategy implements IPromotionStrategy {
   
    public void doPromotion() {
   
        System.out.println("5人团购, 可以优惠");
    }
}
public class PromotionFactory {
   

    private static Map<String, IPromotionStrategy> PROMIOTIONS = new HashMap<String, IPromotionStrategy>();

    private static final IPromotionStrategy EMPTY = new EmptyStrategy();

    static {
   
        PROMIOTIONS.put(PromotionKey.CASHBACK, <
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值