策略模式
定义: 对统一问题的不同解决方案单独封装起来
策略模式举例
最近房租涨的这么猛,就以计算不同地方的房租为例
这里的Calculation就是我们的计算策略
public interface Calculation{
int calculationAverageRent();
}
然后我们算一下深圳和北京这两个地方的平均房租
public class ShenzhenAvaerageRent implements Calculation {
@Override
public int calculationAverageRent() {
//这里只是模拟,省略具体怎么算的。
return 3000;
}
}
public class BeijingAverageRent implements Calculation {
@Override
public int calculationAverageRent() {
//这里只是模拟,省略具体怎么算的。
return 5000;
}
}
我们分别写了两个不同的类,BeijingAverageRent和ShenzhenAvaerageRent来计算北京和深圳的平均房租,这样都是计算平均房租,具体的复杂实现却互不影响。然后写一个具体的计算平均房租的类
public class CalculationAverageRent{
private Calculation calculation;
public void setCalculation(Calculation calculation){
this.calculation = calculation;
}
public Calculation getCalculation(){
return calculation.calculationAverageRent();
}
}
至此策略模式的整个结构就呈现了。就是为了把BeijingAverageRent和ShenzhenAvaerageRent这两个具体的方法独立出来。实现解耦。最后调用就很简单了
使用:
ShenzhenAvaerageRent shenzhenAvaerageRent = new ShenzhenAvaerageRent();
BeijingAverageRent beijingAverageRent = new BeijingAverageRent();
CalculationAverageRent calculationAverageRent = new CalculationAverageRent();
calculationAverageRent.setCalculation(shenzhenAvaerageRent);
int shenzhen = calculationAverageRent.getAverageRent();
calculationAverageRent.setCalculation(beijingAverageRent);
int beijing = calculationAverageRent.getAverageRent();
结构特别简单,但它带来的好处也很明显,算法独立,扩展,修改都很方便,俗称采用不同的策略,由此策略模式名字由此而来。如果不用策略模式,你或许就直接定义两个计算的类来实现,但是,你想想你在调用的时候,你只能是用if else 或者switch来选择北京还是深圳,然后再去调用算法。显然没有策略模式的代码优雅,且扩展性也没这么好
优缺点
优点
- 结构清晰,简单直观
- 扩展性强,耦合度低
- 封装彻底,安全性高
缺点
如果策略很多,那么子类就变得很繁琐
策略模式解析
1821

被折叠的 条评论
为什么被折叠?



