1

策略模式

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();
    }
}
  • 控制台输出:

image-20211013223816483

7.总结

  • 策略模式结合工厂模式减少了if...else代码,提高了代码的效率和可维护性
  • 代码的解耦
  • 策略类中都有共同的行为,不过这个行为的结果不一样

Root
4 声望4 粉丝