策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类,视实际需求是否添加),提供辅助函数。
首先统一接口:
1
2
3
4
5
|
package
com.model.behaviour;
publicinterface
ICalculator {
publicint
calculate(String exp);
}
|
辅助类:
1
2
3
4
5
6
7
8
9
10
11
12
|
package
com.model.behaviour;
publicabstractclass
AbstractCalculator {
publicint
[] split(String exp, String opt) {
String array[] = exp.split(opt);
int
arrayInt[] =
newint
[
2
];
arrayInt[
0
] = Integer.parseInt(array[
0
]);
arrayInt[
1
] = Integer.parseInt(array[
1
]);
return
arrayInt;
}
}
|
三个实现类:
1
2
3
4
5
6
7
8
9
10
|
package
com.model.behaviour;
publicclass
Plus
extends
AbstractCalculator
implements
ICalculator {
@Override
publicint
calculate(String exp) {
int
arrayInt[] = split(exp,
"\\+"
);
return
arrayInt[
0
] + arrayInt[
1
];
}
}
|
1
2
3
4
5
6
7
8
9
10
11
|
package
com.model.behaviour;
publicclass
Minus
extends
AbstractCalculator
implements
ICalculator {
@Override
publicint
calculate(String exp) {
int
arrayInt[] = split(exp,
"\\-"
);
return
arrayInt[
0
] - arrayInt[
1
];
}
}
|
1
2
3
4
5
6
7
8
9
10
|
package
com.model.behaviour;
publicclass
Multiply
extends
AbstractCalculator
implements
ICalculator {
@Override
publicint
calculate(String exp) {
int
arrayInt[] = split(exp,
"\\*"
);
return
arrayInt[
0
]*arrayInt[
1
];
}
}
|
测试类:
1
2
3
4
5
6
7
8
9
10
11
|
package
com.model.behaviour;
publicclass
StrategyTest {
publicstaticvoid
main(String[] args) {
String exp =
"8-2"
;
ICalculator cal =
new
Minus();
int
result = cal.calculate(exp);
System.out.println(exp +
"="
+ result);
}
}
|
策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。