策略模式

定义

定义一组算法,将每个算法都封装起来,并且使它们之间可以互换

代码

策略类,约束算法

1
2
3
public interface Strategy {
void doSomething();
}

策略不同算法的实现

1
2
3
4
5
6
public class ConcreteStrategy1 implements Strategy {
@Override
public void doSomething() {
System.out.println("strategy01");
}
}

1
2
3
4
5
6
public class ConcreteStrategy2 implements Strategy {
@Override
public void doSomething() {
System.out.println("strategy02");
}
}

封装策略类

1
2
3
4
5
6
7
8
9
10
11
public class Context {
private Strategy strategy;

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

public void execute(){
this.strategy.doSomething();
}
}

测试

1
2
3
4
5
6
7
8
9
10
public class ContextTest {

@Test
public void testStrategy(){
Strategy strategy1 = new ConcreteStrategy1();
Context context = new Context(strategy1);
context.execute();
}

}
扩展

策略枚举

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
public enum  Calculator {

ADD("+"){
@Override
public int exec(int a, int b) {
return a+b;
}
},
SUB("-"){
@Override
public int exec(int a, int b) {
return a-b;
}
};


private String value;

Calculator(String value) {
this.value = value;
}

public String getValue() {
return value;
}

public static Calculator getByValue(String value){
for (Calculator calculator : Calculator.values()) {
if(calculator.getValue().equalsIgnoreCase(value)){
return calculator;
}
}
return null;
}

public abstract int exec(int a,int b);

}

测试

1
2
3
4
5
6
7
8
9
10
11
public class CalculatorTest {

@Test
public void testCalulator(){
int addResult = Calculator.getByValue("+").exec(10,20);
System.out.println(addResult);
int subResult = Calculator.getByValue("-").exec(20,5);
System.out.println(subResult);
}

}