策略模式

“策略模式”:__定义了一系列的算法并提供运行时动态更改算法的能力,保证了客户端代码的简洁性__。

实现方式:

  1. 创建__策略接口__;
  2. 创建多个__策略类__继承__策略接口__并通过不同算法实现接口中声明的方法;
  3. 创建一个__消费者类__,它必须存储一个__策略对象__的引用并对外提供一个可修改该引用的方法;
  4. 在执行环境的上下文通过动态的更改__消费者对象__中存储的__策略对象__引用来达到动态更改算法的目的;
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
76
77
78
79
80
import java.util.ArrayList;
import java.util.List;

public class StrategyPatternWiki {
public static void main(final String[] arguments) { // 执行环境上下文
Customer firstCustomer = new Customer(new NormalStrategy());

// Normal billing
firstCustomer.add(1.0, 1);

// Start Happy Hour
firstCustomer.setStrategy(new HappyHourStrategy());
firstCustomer.add(1.0, 2);

// New Customer
Customer secondCustomer = new Customer(new HappyHourStrategy());
secondCustomer.add(0.8, 1);
// The Customer pays
firstCustomer.printBill();

// End Happy Hour
secondCustomer.setStrategy(new NormalStrategy());
secondCustomer.add(1.3, 2);
secondCustomer.add(2.5, 1);
secondCustomer.printBill();
}
}

// 消费者类
class Customer {

private List<Double> drinks;
private BillingStrategy strategy; // 策略对象的引用

public Customer(final BillingStrategy strategy) {
this.drinks = new ArrayList<Double>();
this.strategy = strategy;
}

public void add(final double price, final int quantity) {
drinks.add(strategy.getActPrice(price*quantity)); // 策略对象上方法的调用
}

// Payment of bill
public void printBill() {
double sum = 0;
for (Double i : drinks) {
sum += i;
}
System.out.println("Total due: " + sum);
drinks.clear();
}

// Set Strategy 策略对象引用的修改方法
public void setStrategy(final BillingStrategy strategy) {
this.strategy = strategy;
}

}

// 策略接口
interface BillingStrategy {
double getActPrice(final double rawPrice);
}

// Normal billing strategy (unchanged price) 策略类
class NormalStrategy implements BillingStrategy {
@Override
public double getActPrice(final double rawPrice) { // 算法实现
return rawPrice;
}
}

// Strategy for Happy hour (50% discount) 策略类
class HappyHourStrategy implements BillingStrategy {
@Override
public double getActPrice(final double rawPrice) { // 算法实现
return rawPrice*0.5;
}
}