设计模式:策略模式

策略模式解析

策略模式

定义: 对统一问题的不同解决方案单独封装起来

策略模式举例

最近房租涨的这么猛,就以计算不同地方的房租为例
这里的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来选择北京还是深圳,然后再去调用算法。显然没有策略模式的代码优雅,且扩展性也没这么好

优缺点

优点
  • 结构清晰,简单直观
  • 扩展性强,耦合度低
  • 封装彻底,安全性高
缺点

如果策略很多,那么子类就变得很繁琐

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值