学习路径: 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中的元素,这里还是可以进行优化的。