设计模式-策略模式

某个市场人员接到单后的报价策略(CRM系统中常见问题)。报价策略很复杂,可以简单作如下分类:
• 普通客户小批量报价
• 普通客户大批量报价
• 老客户小批量报价
• 老客户大批量报价
具体选用哪个报价策略,这需要根据实际情况来确定。这时候,我们采用策略模式即可。

我们先可以采用条件语句处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public double getPrice(String type, double price){
if(type.equals("普通客户小批量")){
System.out.println("不打折,原价");
return price;
}else if(type.equals("普通客户大批量")){
System.out.println("打九折");
return price*0.9;
}else if(type.equals("老客户小批量")){
System.out.println("打八五折");
return price*0.85;
}else if(type.equals("老客户大批量")){
System.out.println("打八折");
return price*0.8;
}
return price;
}

但类型特别多,算法比较复杂时,整个条件控制代码会变得很长,难于维护。

策略模式对应于解决某一个问题的一个算法族,允许用户从该算法族中任选一个算法解决某一问题,同时可以方便的更换算法或者增加新的算法。并且由客户端决定调用哪个算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//策略接口
public interface Strategy {
double getPrice(double standardPrice);
}

//新客户小批量
public class NewCustomerFew implements Strategy{
@Override
public double getPrice(double standardPrice) {
System.out.println("不打折原价");
return standardPrice;
}
}


//新客户大批量
public class NewCustomerLarge implements Strategy{
@Override
public double getPrice(double standardPrice) {
System.out.println("打九折!");
return standardPrice*0.9;
}
}

//老客户小批量
public class OldCustomerFew implements Strategy{
@Override
public double getPrice(double standardPrice) {
System.out.println("打85折");
return standardPrice*0.85;
}
}

//老客户大批量
public class OldCustomLarge implements Strategy{
@Override
public double getPrice(double standardPrice) {
System.out.println("打8折");
return standardPrice*0.8;
}
}

//上下文类
//负责和具体的策略类交互,是的客户端和算法独立
public class Context {
private Strategy strategy; //当前采用的算法对象

//通过构造器注入
public Context(Strategy strategy) {
this.strategy = strategy;
}

//通过set方法注入
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}

public void printPrice(double s){
System.out.println("价格:"+strategy.getPrice(s));
}
}

//测试
public class test {
public static void main(String[] args) {
Strategy s1 = new OldCustomerFew();
Strategy s2 = new OldCustomLarge();
Context ctx = new Context(s1);
Context ctx2 = new Context(s2);
int standardPrice = 1000;

ctx.printPrice(standardPrice);
ctx2.printPrice(standardPrice);
}
}

• 本质:分离算法,选择实现。
• 开发中常见的场景:JAVASE中GUI编程中,布局管理;Spring框架中,Resource接口,资源访问策略;javax.servlet.http.HttpServlet#service()