定义
将一系列的算法封装起来,而且可以相互替换。让算法独立于使用它的客户而独立变化。
使用场景
- 针对同一问题有多种处理方式,而仅仅是方式有差异。
- 需要安全的封装多种同一类型的操作时。
- 出现同一抽象类有多个子类,需要使用switch语句或者if语句选择时。
举例
其实有很多例子,我这里想到买菜的场景。
来看代码简单实现:
public interface ICalculator {
/**
* 根据重量计算最终价格
* @param weight 重量kg
* @return 最终的价格
*/
float calculatorPrice(float weight);
}
public class Apple implements ICalculator {
@Override
public float calculatorPrice(float weight) {
float nowPrice = 1.5f;
return nowPrice * weight;
}
}
public class Orange implements ICalculator {
@Override
public float calculatorPrice(float weight) {
float nowPrice = 2.0f;
return nowPrice * weight;
}
}
public class PriceCalculator {
private ICalculator calculator;
public void setCalculator(ICalculator calculator){
this.calculator = calculator;
}
public float calculatorPrice(float weight){
return calculator.calculatorPrice(weight);
}
//省事了点,调用直接在类中了
@Test
public void checkOut(){
PriceCalculator calculator = new PriceCalculator();
calculator.setCalculator(new Apple());
System.out.println("买1斤苹果花的钱》》"+calculator.calculatorPrice(1f));
calculator.setCalculator(new Orange());
System.out.println("买1斤桔子花的钱》》"+calculator.calculatorPrice(1f));
}
}
总结
策略模式主要用来分离算法,在相同的抽象条件拥有不同的策略。充分展示了开闭原则,使我们的代码可以有很好的扩展性。
优点
- 结构清晰、使用简单;
- 耦合性低,好扩展;
- 封装性好,数据隐蔽。
缺点
- 算法多了,子类也就多了。