目录
一、策略模式应用场景
策略模式定义:策略模式(Strategy Pattern)是指定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化不会影响到使用算法的用户。
策略模式应用场景:
1、假如一个系统中有很多类,而他们的区别仅仅在于他们的行为不同。
2、一个系统需要动态的在几种算法中选一种。
例:选择支付方式,选择促销活动方式
二、策略模式实现
代码实现:(就用常见的选择促销方式)
优惠策略会有很多种可能 如:领取优惠券抵扣、返现促销等等。
首先创建一个促销策略抽象PromotionStrategy
public interface PromotionStrategy {
void doPromtion();
}
然后分别创建优惠卷策略类,促销返现策略类以及无任何优惠类。
public class CouponStrategy implements PromotionStrategy {
@Override
public void doPromtion() {
System.out.println("优惠卷");
}
}
public class CashbackStrategy implements PromotionStrategy {
@Override
public void doPromtion() {
System.out.println("返现促销活动");
}
}
public class EmptyStrategy implements PromotionStrategy {
@Override
public void doPromtion() {
System.out.println("无任何优惠");
}
}
然后再创建促销活动方案类PromotionActivity
public class PromtionActivity {
private PromotionStrategy PromotionStrategy;
public PromtionActivity(PromotionStrategy PromotionStrategy){
this.PromotionStrategy=PromotionStrategy;
}
public void execute(){
PromotionStrategy.doPromtion();
}
}
最基本的策略模式已经完成,但是为了我们更好的使用可以结合工厂以及单例模式进行进一步的优化:
public class PromotionStrategyFactory {
//登记已有策略
private static Map<String, PromotionStrategy> PROMTION_STEATEGY_MAP = new HashMap<String, PromotionStrategy>();
//添加策略
static {
PROMTION_STEATEGY_MAP.put(PromotionKey.COUPON, new CouponStrategy());
PROMTION_STEATEGY_MAP.put(PromotionKey.CASHBACK, new CashbackStrategy());
}
//没有使用任何策略
private static final PromotionStrategy NOM_PROMTION = new EmptyStrategy();
//构造私有化
private PromotionStrategyFactory() {
}
//对外提供一个方法返回对于的策略
public static PromotionStrategy getPromotionStrategy(String promotionKey) {
PromotionStrategy PromotionStrategy = PROMTION_STEATEGY_MAP.get(promotionKey);
return PromotionStrategy == null ? NOM_PROMTION : PromotionStrategy;
}
//已有的策略
private interface PromotionKey {
String COUPON = "COUPON";
String CASHBACK = "CASHBACK";
}
测试方法:
public class PromotionStrategyTest {
public static void main(String[] args) {
String promotionKey = "COUPON";
PromotionStrategy PromotionStrategy=PromotionStrategyFactory.getPromotionStrategy(promotionKey);
PromtionActivity promtionActivity = new PromtionActivity(PromotionStrategy);
promtionActivity.execute();
}
}
三、策略模式的优缺点
策略模式的优点:
1、策略模式符合开闭原则。
2、避免使用多重条件转移语句,如:if....else...语句,switch语句。
3、使用策略模式可以提高算法的保密性和安全性。
缺点:
1、客户端必须知道所以策略,并自行觉定使用哪一个。
2、代码中会增加非常多策略类,增加代码的维护难度。