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