策略模式介绍

##策略模式
###1.背景

  • 在软件开发过程中常常遇到这种情况:实现一个功能可以有多重算法或者策略,我们根据实际情况选择不同的算法来完成。针对这种情况,一种常规的方法是将多重算法写在一个类中。创建多个方法,一个算法对一个以具体的算法。也可以吧这些算反封装到一个统一的类中,通过if…else语句来选择具体的算法,这种方法我们可以称为硬编码
  • 缺点:当多个算法集中在一个类中时,这个类就会变得臃肿,这个类的维护成本会变高,在维护是也更容易引发错误。如果我们需要增加一种新的排序算法,需要修改封装算法的源代码。这就违反了之前说的OCP原则和单一职责原则。
  • 如果将这些算法或者策略抽象出来,提供一个统一的接口,不同的算方法或者策略有不同的实现类,这样在程序客户端就可以通过注入不同的实现对象或者策略的动态替换,这种模式的可拓展性,可维护性就会更高,也就是我们说的策略模式。

###2.定义

  • 策略模式定义了一系列算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
    ###3.使用场景
  • 1.针对同一类型问题的多种处理方式,仅仅是具体行为有差异时。
  • 2.需要安全的封装多种同一类型的操作时。
  • 3.出现同一抽象类有多个子类,而又需要使用if-else或者switch-case来选择具体子类时
    ###4.UML图成员
  • 1.Context 用来操作策略模式的上下文环境
  • 2.Stragety 策略的抽象
  • 3.ConcreteStragetyA,ConcreteStragetyB-具体的策略实现

###5.简单实现

  • 公交车,地铁的计费demo:
    public class PriceCalculator {
    //公交车
    private static final int BUS = 1;
    //地铁
    private static final int SUBWAY = 2;
    public static void main(String[] args) {
    }
    /**
    * 公交车,10公里一元,超过10公里后每加1元可以乘坐5公里
    * @param km
    * @return
    /
    private int busPrice(int km) {
    //超过10公里的总距离
    int extraTotal = km-10;
    //超过的距离是5公里的倍数
    int extraFactor = extraTotal/5;
    //超过的距离对5取的余数
    int fraction = extraTotal%5;
    //价格计算
    int price = 1+extraFactor
    1;
    return fraction>0?++price:price;
    }
    private int subwayPrice(int km) {
    if (km < 6) {
    return 3;
    } else if (km > 6 && km < 12) {
    return 4;
    } else if (km > 12 && km < 22) {
    return 5;
    } else {
    //其他的简化为6元,666嘛
    return 6;
    }
    }
    }
    //根据不同的出行方式计费
    int calculatePrice(int km, int type) {
    if (type == BUS) {
    return busPrice(km);
    } else if (type == SUBWAY) {
    return subwayPrice(km);
    }
    return 0;
    }

  • 分析PriceCalculator类很明显并不是单一职责,首先它承担了计算公交车和地铁乘坐价格的职责,另一个问题就是通过if-else的形式来判断使用哪种计算形式。当我另外增加一种出行方式的时候,例如,出租车,那么就需要在PriceCalcutor类中添加一个方法来计算出租车出行的价格,并且在calculatePrice(int km)中添加一个判断大致代码如下

    private static final int TAXI = 3;
    /**
    *

    • @param km
    • @return
      /
      private int taxiPrice(int km) {
      return km
      2;
      }

    int calculatePrice(int km, int type) {
    if (type == BUS) {
    return busPrice(km);
    } else if (type == SUBWAY) {
    return subwayPrice(km);
    } else if (type == TAXI) {
    return taxiPrice(km);
    }
    return 0;
    }

##上述代码的缺点:1.逻辑混乱,容易出错,当价格的计算方法变化时就需要改变这个类的代码。该代码可能是多个计算方法公用的,这时候就容易引入错误!在增加if-else判断过程中,手动复制代码的方式更加会造成引入错误。2.代码变得臃肿,难以维护!

  • 策略模式的代码实现
    public interface CalculateStragety {
    /**
    * 按距离来计算价格
    * @param km 公里
    * @return 总价格
    /
    int calculatePrice(int km);
    }
    public class BusStragety implements CalculateStragety{
    /
    *
    * 公交车计算价格
    * @param km 公里
    * @return
    /
    @Override
    public int calculatePrice(int km) {
    //超过10公里的总距离
    int extraTotal = km-10;
    //超过的距离是5公里的倍数
    int extraFactor = extraTotal/5;
    //超过的距离对5取的余数
    int fraction = extraTotal%5;
    //价格计算
    int price = 1+extraFactor
    1;
    return fraction>0?++price:price;
    }
    }
    public class SubwayStragety implements CalculateStragety{
    @Override
    public int calculatePrice(int km) {
    if (km < 6) {
    return 3;
    } else if (km > 6 && km < 12) {
    return 4;
    } else if (km > 12 && km < 22) {
    return 5;
    } else {
    //其他的简化为6元,666嘛
    return 6;
    }
    }
    }

  • 我们再创建一个Context角色的类,这里命名为TrafficCalculator,具体代码如下:
    public class TrafficCalculator {
    public static void main(String args) {
    TrafficCalculator trafficCalculator = new TrafficCalculator();
    trafficCalculator.setStrategy(new BusStragety());
    System.out.println(“公交车费用为:”+trafficCalculator.calculatorPrice(15));
    }
    private CalculateStragety mCalculateStragety;
    public void setStrategy(CalculateStragety calculateStragety) {
    this.mCalculateStragety = calculateStragety;
    }
    public int calculatorPrice(int km) {
    return mCalculateStragety.calculatePrice(km);
    }
    }

  • 经过这样重构后,去掉了各种的if-else语句,结构变得更加清晰。功能的拓展性也变得更加强!如果需要增加一个出租车策略类,则可以设置给TrafficCalculator,最好直接用Trafficcalculator对象进行计算。代码实例如下:

  • 、、、
    public class TaxiStrategy implements CalculateStragety{
    @Override
    public int calculatePrice(int km) {
    return km*2;
    }
    }

  • 将策略注入到T让非常Calculator中
    public class TrafficCalculator {
    public static void main(String args) {
    TrafficCalculator trafficCalculator = new TrafficCalculator();
    trafficCalculator.setStrategy(new TaxiStrategy());
    System.out.println(“TAXI费用为:”+trafficCalculator.calculatorPrice(15));
    }
    private CalculateStragety mCalculateStragety;
    public void setStrategy(CalculateStragety calculateStragety) {
    this.mCalculateStragety = calculateStragety;
    }
    public int calculatorPrice(int km) {
    return mCalculateStragety.calculatePrice(km);
    }
    }

####分析:

  • 1.通过上述的实例,可以清晰的看出二者的区别。前者通过if-else的方式解决问题,虽然简单,层级单一,但暴漏的问题很明显:代码臃肿,难以升级和维护,没有结构可言。后者通过建立抽象,将不同的策略构建成一个具体的策略实现,通过不同的策略实现算法替换。
  • 简化逻辑,和结构
  • 增加了系统的可读性,稳定性,拓展性
  • 业务逻辑更清晰,拓展更加方便。

##6.Android源码中策略模式的实现

##7,深入属性动画

##8,策略模式实战应用

##9总结
-策略模式主要用来分离算法,在相同的行为抽象下有不同的具体实现策略。这个模式很好的演示了开闭原则,也就是定义抽象,注入不同的实现从而达到很好的可拓展性。

  • 优点:

  • 1.结构清晰明了,使用简单直观

  • 2.耦合度相对而言简单,拓展方便

  • 3.操作封装更为彻底,数据更为安全;

  • 缺点:

  • 随着策略的增加,子类也会变的繁多。

  • 还有深度总结需要进行。目前先保持进度。预备下一个模式!

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...