一.定义与类型
1.定义:定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使用算法的用户
2.类型:行为型
二.适用场景
1.系统有很多类,而他们的区别仅仅在于他们的行为不同
2.一个系统需要动态地在几种算法中选择一种
三.优点
1.开闭原则
2.避免使用多重条件转移语句
3.提高算法的保密性和安全性
四.缺点
1.客户端必须知道所有的策略类,并自行决定使用哪一个策略类
2.产生很多策略类
五.UML类图
六.代码
PromotionStrategy.java
package com.caomingyu.autotest.strategy;
public interface PromotionStrategy {
void doPromotion();
}
FanXianPromotionStrategy.java
package com.caomingyu.autotest.strategy;
public class FanXianPromotionStrategy implements PromotionStrategy {
public void doPromotion() {
System.out.println("返现促销,返回的金额存放到慕课网用户的余额中");
}
}
ManJianPromotionStrategy.java
package com.caomingyu.autotest.strategy;
public class ManJianPromotionStrategy implements PromotionStrategy {
public void doPromotion() {
System.out.println("满减促销,满200减20元");
}
}
LiJianPromotionStrategy.java
package com.caomingyu.autotest.strategy;
public class LiJianPromotionStrategy implements PromotionStrategy {
public void doPromotion() {
System.out.println("立减促销,课程的价格直接减去配置的价格");
}
}
EmptyPromotionStrategy.java
package com.caomingyu.autotest.strategy;
public class EmptyPromotionStrategy implements PromotionStrategy {
public void doPromotion() {
System.out.println("无促销活动");
}
}
PromotionActivity.java
package com.caomingyu.autotest.strategy;
public class PromotionActivity {
private PromotionStrategy promotionStrategy;
public PromotionActivity(PromotionStrategy promotionStrategy) {
this.promotionStrategy = promotionStrategy;
}
public void excutePromotionStrategy(){
promotionStrategy.doPromotion();
}
}
PromotionStrategyFactory.java
package com.caomingyu.autotest.strategy;
import java.util.HashMap;
import java.util.Map;
//结合工厂类
public class PromotionStrategyFactory {
private static Map<String, PromotionStrategy> PROMOTION_STRATEGY_MAP = new HashMap<String, PromotionStrategy>();
private static final PromotionStrategy NON_PROMOTION = new EmptyPromotionStrategy();
static {
PROMOTION_STRATEGY_MAP.put(PromotionKey.LIJIAN, new LiJianPromotionStrategy());
PROMOTION_STRATEGY_MAP.put(PromotionKey.FANXIAN, new FanXianPromotionStrategy());
PROMOTION_STRATEGY_MAP.put(PromotionKey.MANJIAN, new ManJianPromotionStrategy());
}
private PromotionStrategyFactory() {
}
public static PromotionStrategy getPromotionStrategy(String promotionKey){
PromotionStrategy promotionStrategy = PROMOTION_STRATEGY_MAP.get(promotionKey);
return promotionStrategy == null ? NON_PROMOTION : promotionStrategy;
}
private interface PromotionKey{
String LIJIAN = "LIJIAN";
String FANXIAN = "FANXIAN";
String MANJIAN = "MANJIAN";
}
}
Test.java
package com.caomingyu.autotest.strategy;
public class Test {
public static void main(String[] args) {
String promotionKey = "LIJIAN";
PromotionActivity promotionActivity = new PromotionActivity(PromotionStrategyFactory.getPromotionStrategy(promotionKey));
promotionActivity.excutePromotionStrategy();
}
}