策略模式

1 概念

1 定义

在策略模式定义了一系列算法或策略,并将每个算法封装在独立的类中,使得它们可以互相替换。通过使用策略模式,可以在运行时根据需要选择不同的算法,而不需要修改客户端代码。

类型:行为型

2 应用场景

  • 一个系统需要动态在几种策略中选择一种
  • 系统很多类,区别仅仅是行为不同

3 优缺点

优点:

  • 符合开闭原则
  • 避免大量使用if…else, switch..case
  • 提高算法的保密性和安全性

缺点:

  • 客户端必须知道所有的策略类,并自行决定使用哪个类
  • 产生很多策略类

2 代码实现

场景:慕课网活动促销,有多种方式:满减,返现,立减等,双11和618都采取不同的策略。

1
2
3
public interface PromotionStrategy {
void doPromotion();
}
1
2
3
4
5
6
public class EmptyPromotionStrategy implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("无促销活动");
}
}
1
2
3
4
5
6
public class LiJianPromotionStrategy implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("立减促销,课程的价格直接减去配置的价格");
}
}
1
2
3
4
5
6
public class FanXianPromotionStrategy implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("返现促销,返回的金额存放到慕课网用户的余额中");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 促销活动
public class PromotionActivity {
// 促销策略
private PromotionStrategy promotionStrategy;

public PromotionActivity(PromotionStrategy promotionStrategy) {
this.promotionStrategy = promotionStrategy;
}

// 执行促销
public void executePromotionStrategy(){
promotionStrategy.doPromotion();
}
}

1
2
3
4
5
6
7
8
9
public class Test {
public static void main(String[] args) {
PromotionActivity promotionActivity618 = new PromotionActivity(new LiJianPromotionStrategy());
PromotionActivity promotionActivity1111 = new PromotionActivity(new FanXianPromotionStrategy());

promotionActivity618.executePromotionStrategy();
promotionActivity1111.executePromotionStrategy();
}
}

输出:

立减促销,课程的价格直接减去配置的价格
返现促销,返回的金额存放到慕课网用户的余额中

代码演进

如果需要根据传过来的key,去选择对应的策略,使用共厂模式演进。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class PromotionStrategyFactory {
private static Map<String,PromotionStrategy> PROMOTION_STRATEGY_MAP = new HashMap<String, PromotionStrategy>();
static {
PROMOTION_STRATEGY_MAP.put(PromotionKey.LIJIAN,new LiJianPromotionStrategy());
PROMOTION_STRATEGY_MAP.put(PromotionKey.FANXIAN,new FanXianPromotionStrategy());
}

// 避免每次进来都需要new
private static final PromotionStrategy NON_PROMOTION = new EmptyPromotionStrategy();

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";
}
}
1
2
3
4
5
6
7
public class Test {
public static void main(String[] args) {
String promotionKey = "LIJIAN";
PromotionActivity promotionActivity = new PromotionActivity(PromotionStrategyFactory.getPromotionStrategy(promotionKey));
promotionActivity.executePromotionStrategy();
}
}

输出:

立减促销,课程的价格直接减去配置的价格


策略模式
http://example.com/策略模式/
作者
Panyurou
发布于
2023年10月4日
许可协议