动机:算法经常改变,算法编写到对象中会使得对象复杂,而且有时候支持不适用的算法也是一种负担
(if-else过多的时候,需要小心,判断条件是否会改变)
public enum country{
china,
japan,
france,
africa//改变
}
class sale{
TaxBase tb;
public void calculate(){
if(tb == country.china){
...
}else if(tb == country.japan){
...
}else if(tb == country.france){
...
}else if(tb == country.africa){
...
//改变
}
}
}
这样一来,在二进制层面上,违背了设计原则中的开闭原则,采用策略模式改写后
class TaxStrategy{
protected double calculate(){}
}
class ChinaTax{
@Override
protected double calculate(){
...
}
}
class JapanTax{
@Override
protected double calculate(){
...
}
}
class sale{
TaxStrategy ts;
public sale(StrategyFactory strategyFactory){
this.ts=strategyFactory.newStrategy();
}
public double calculate(){
ts.calculate();
...
}
}