策略模式
1.定义与类型
- 定义:定义了算法家族,别离封装起来,让他们之间能够相互转换,此模式让算法的变动不会影响到应用算法的用户
- if...else
- 类型:行为型
2.实用场景
- 零碎有很多类,而他们的区别仅仅在于他们的行为不同
- 一个零碎须要动静地在几种算法中抉择一种
3.长处
- 开闭准则
- 防止应用多种条件转移语句
- 进步算法的保密性和安全性
4.毛病
- 客户端必须晓得所有的策略类,并自行决定应用哪一个策略类
- 产生很多策略类
5.相干设计模式
- 策略模式 和 工厂模式
- 策略模式 和 状态模式
6.Coding
策略模式加工厂模式
- 创立策略接口Promotion
public interface PromotionStrategy { void doPromotion();}
- 创立一系列促销策略
public class FanXianPromotionStrategy implements PromotionStrategy{ @Override public void doPromotion() { System.out.println("返现促销,返回的余额寄存到用户余额中!"); }}
public class LiJianPromotionStrategy implements PromotionStrategy { @Override public void doPromotion() { System.out.println("立减促销,课程的价格间接减去配置的价格"); }}
public class ManJianPromotionStrategy implements PromotionStrategy{ @Override public void doPromotion() { System.out.println("满减促销:满200减20"); }}
- 创立促销流动:用来执行促销策略的类
public class PromotionActivity { private PromotionStrategy strategy; public PromotionActivity(PromotionStrategy strategy){ this.strategy = strategy; } public void executeStrategy(){ strategy.doPromotion(); }}
- 创立促销策略工厂
/** * @program: design_pattern * @description: 促销策略工厂 * @create: 2021-10-13 22:23 **/public class PromotionStrategyFactory { /** 私有化结构器 */ private PromotionStrategyFactory(){} private static final Map<String,PromotionStrategy> PROMOTION_STRATEGY_MAP = new HashMap<>(); //初始化工厂 static { PROMOTION_STRATEGY_MAP.put(PromotionType.FANXIAN,new FanXianPromotionStrategy()); PROMOTION_STRATEGY_MAP.put(PromotionType.LIJIAN,new LiJianPromotionStrategy()); PROMOTION_STRATEGY_MAP.put(PromotionType.MANJIAN,new ManJianPromotionStrategy()); } /** 对外提供获取策略的办法 */ public static PromotionStrategy getPromotionStrategy(String promotionKey){ PromotionStrategy promotionStrategy = PROMOTION_STRATEGY_MAP.get(promotionKey); return promotionStrategy == null?null:promotionStrategy; } private interface PromotionType{ String LIJIAN = "LIJIAN"; String MANJIAN = "MANJIAN"; String FANXIAN = "FANXIAN"; }}
- 测试类
public class Test { public static void main(String[] args) { String promotionKey = "LIJIAN"; PromotionActivity promotionActivity = new PromotionActivity(PromotionStrategyFactory.getPromotionStrategy(promotionKey)); promotionActivity.executeStrategy(); }}
- 控制台输入:
7.总结
- 策略模式联合工厂模式缩小了if...else代码,进步了代码的效率和可维护性
- 代码的解耦
- 策略类中都有独特的行为,不过这个行为的后果不一样