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

策略模式

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

简单来说,只要你写过程序就用过策略模式,不要说没用过,难道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.5
2块钱7折后的价格:1.4

总结

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

github代码地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 场景问题# 1.1 报价管理## 向客户报价,对于销售部门的人来讲,这是一个非常重大、非常复杂的问题,对不同的...
    七寸知架构阅读 5,138评论 9 62
  • 1 场景问题 1.1 报价管理 向客户报价,对于销售部门的人来讲,这是一个非常重大、非常复杂的问题,对不同的客户要...
    4e70992f13e7阅读 3,147评论 2 16
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,785评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,079评论 19 139
  • 框中鱼 逐步迎 相嬉乐 相吐沫 相形相触跃水面 日光映影随框下 只留欢乐在其中
    夏沫星空雨阅读 198评论 0 2