Android设计模式之(6)----策略模式

来源:互联网 发布:如何进行软件开发 编辑:程序博客网 时间:2024/06/02 05:54

策略模式

一个功能的效果,有不同的算法与策略,根据不同的选择选择不同的结果。

简单来说,只要你写过程序就用过策略模式,不要说没用过,难道if-else(switch)没用过吗…..

if-else在其实就是一个策略模式的体现,根据不同的选择处理不同的结果。

问题

如果把所有的方法全部用if-else(switch)来处理,从功能上说没问题,但是冲代码层面的维护与使用来说,if-else多了之后会让类变的过于庞大,阅读不利,修改困难

解决问题

使用策略模式,定义统一接口,每一个不同的功能(if-else)实现接口做一个具体类,外部调用具体类来达到不同的结果。

使用场景

  • 同一个问题,有不同的解决方案
  • 一个类有多个if-else的判断处理结果
  • 封装SDK时上层处理结果返回的情况,调用者关心结果,不关注实现过程
  • 列入Android源码中的动画的TimeInterpolator,ListView的适配器

代码实现

有一个商品售卖,在售卖过程中,要根据不同的用户给予不同的价格(半价,8折,7折等等),在知道用户的前提下,如何直接给予价格呢?

(一)价格接口的实现

public interface PriceStrategy {    int  setPrice(int price);}

(二)实现具体的价格类

7折:

public class seventPriceStrategy implements PriceStrategy {    @Override    public Double setPrice(int price) {        return 0.7 * price;    }}

5折:

public class HalfPriceStrategy implements PriceStrategy {    @Override    public Double setPrice(int price) {        return 0.5 * price;    }}

(三)价格算法管理类

public class PriceAlgorithm {    private PriceStrategy priceStrategy;    public PriceStrategy getPriceStrategy() {        return priceStrategy;    }    public void setPriceStrategy(PriceStrategy priceStrategy) {        this.priceStrategy = priceStrategy;    }    public Double getPrice(int price) {        if(priceStrategy!=null){            return priceStrategy.setPrice(price);        }        return null;    }}

传入具体的实现类,获取返回接口

(四)调用方式

 PriceAlgorithm priceAlgorithm = new PriceAlgorithm(); priceAlgorithm.setPriceStrategy(new HalfPriceStrategy()); System.out.print("\n" + "1块钱" + "5折后的价格:" +  String.valueOf(priceAlgorithm.getPrice(1))); PriceAlgorithm priceAlgorithm2 = new PriceAlgorithm(); priceAlgorithm2.setPriceStrategy(new seventPriceStrategy()); System.out.print("\n" + "2块钱" + "7折后的价格:" + String.valueOf(priceAlgorithm2.getPrice(2)));

(五)显示结果

1块钱5折后的价格:0.52块钱7折后的价格:1.4

总结

使用策略模式之后的维护只需要维护具体的实现类,如果有新增的方式,只需要扩展实现具体类即可,便于维护使用。

github代码地址

原创粉丝点击