Strategy Pattern

Strategy Pattern

  1. 体现了两个非常基本的面相对象设计原则
  • 封装变化的概念
  • 编程中使用接口,而不是对接口的实现
  1. 定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。
  2. 策略模式使这些算法在客户端调用它们的时候能够互不影响地变化
  3. 组成:
  • 抽象策略角色
  • 具体策略角色:包装了相关的算法和行为
  • 环境角色:持有一个策略类的引用,最终给客户端调用的。
1
2
3
4
5
6
7
/**
* 抽象策略角色
*/
public interface Strategy {
int caculate(int a, int b);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 具体策略角色
*/
public class AddStrategy implements Strategy {
@Override
public int caculate(int a, int b) {
return a + b;
}
}
/**
* 具体策略角色
*/
public class SubtractStrategy implements Strategy {
@Override
public int caculate(int a, int b) {
return a - b;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 环境
*/
public class Environment {
private Strategy strategy;
public Environment(Strategy strategy) {
this.strategy = strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public int caculate(int a, int b) {
return strategy.caculate(a, b);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
/**
* 调用
*/
public class Client {
public static void main(String[] args) {
AddStrategy addStrategy = new AddStrategy();
Environment environment = new Environment(addStrategy);
System.out.println(environment.caculate(1, 2));
}
}