一个类的行为或者算法可以在运行时更改,策略模式改变对象的执行算法。属于行为型模式。

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
public class StrategyPattern {

public static void main(String[] args) {

Context context = new Context();
// context.setStrategy(new AndStrategy());
context.setStrategy(new OrStrategy());
context.deploy(2,1);

}

//环境类,算法执行的上下文环境
static class Context {
private Strategy strategy;

public Context(Strategy strategy) {
this.strategy = strategy;
}

public Context() {
}

public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}

public void deploy(int a, int b) {
if (strategy != null) {
int result = strategy.deploy(a, b);
System.out.println("result:" + result);
}
}
}

//抽象策略类
interface Strategy {
int deploy(int a, int b);
}

//具体策略类
static class AndStrategy implements Strategy {

public int deploy(int a, int b) {
return a & b;
}
}
//具体策略类
static class OrStrategy implements Strategy {

public int deploy(int a, int b) {
return a | b;
}
}

}

策略模式解决的问题

1.可以防止硬编码,if_else构成的多种case的行为;
2.系统需要动态的在几种算法中选择一种;
3.不希望提供具体的算法逻辑。

优点:

1.算法可以灵活切换;
2.避免复杂的条件判断;
3.算法扩展性好。

优点:

1.具体策略类会越来越多;

实际应用场景:
三方应用的初始化,有友盟(区分线上线下版本内部会日志打印上报时机)、BlockCanary;
源码中RecyclerView或者LisView的Adapter,每个具体的列表就是一种策略,构建列表时使用具体的策略来完成展示。

感谢

https://www.runoob.com/design-pattern/strategy-pattern.html