策略模式定义了一些列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变换。

假设我们要出去旅游,而去旅游出行的方式有很多,有步行,有坐火车,有坐飞机等等。而如果不使用任何模式,我们的代码可能就是这样子的。

  1. public class TravelStrategy {
  2. enum Strategy{
  3. WALK,PLANE,SUBWAY
  4. }
  5. private Strategy strategy;
  6. public TravelStrategy(Strategy strategy){
  7. this.strategy=strategy;
  8. }
  9. public void travel(){
  10. if(strategy==Strategy.WALK){
  11. print("walk");
  12. }else if(strategy==Strategy.PLANE){
  13. print("plane");
  14. }else if(strategy==Strategy.SUBWAY){
  15. print("subway");
  16. }
  17. }
  18. public void print(String str){
  19. System.out.println("出行旅游的方式为:"+str);
  20. }
  21. public static void main(String[] args) {
  22. TravelStrategy walk=new TravelStrategy(Strategy.WALK);
  23. walk.travel();
  24. TravelStrategy plane=new TravelStrategy(Strategy.PLANE);
  25. plane.travel();
  26. TravelStrategy subway=new TravelStrategy(Strategy.SUBWAY);
  27. subway.travel();
  28. }
  29. }

这样做有一个致命的缺点,一旦出行的方式要增加,我们就不得不增加新的else if语句,而这违反了面向对象的原则之一,对修改封闭。而这时候,策略模式则可以完美的解决这一切。

首先,需要定义一个策略接口。

  1. public interface Strategy {
  2. void travel();
  3. }

然后根据不同的出行方式实行对应的接口

  1. public class WalkStrategy implements Strategy{
  2. @Override
  3. public void travel() {
  4. System.out.println("walk");
  5. }
  6. }
  1. public class PlaneStrategy implements Strategy{
  2. @Override
  3. public void travel() {
  4. System.out.println("plane");
  5. }
  6. }
  1. public class SubwayStrategy implements Strategy{
  2. @Override
  3. public void travel() {
  4. System.out.println("subway");
  5. }
  6. }

此外还需要一个包装策略的类,并调用策略接口中的方法

  1. public class TravelContext {
  2. Strategy strategy;
  3. public Strategy getStrategy() {
  4. return strategy;
  5. }
  6. public void setStrategy(Strategy strategy) {
  7. this.strategy = strategy;
  8. }
  9. public void travel() {
  10. if (strategy != null) {
  11. strategy.travel();
  12. }
  13. }
  14. }

测试一下代码

  1. public class Main {
  2. public static void main(String[] args) {
  3. TravelContext travelContext=new TravelContext();
  4. travelContext.setStrategy(new PlaneStrategy());
  5. travelContext.travel();
  6. travelContext.setStrategy(new WalkStrategy());
  7. travelContext.travel();
  8. travelContext.setStrategy(new SubwayStrategy());
  9. travelContext.travel();
  10. }
  11. }

输出结果如下

  1. plane
  2. walk
  3. subway

可以看到,应用了策略模式后,如果我们想增加新的出行方式,完全不必要修改现有的类,我们只需要实现策略接口即可,这就是面向对象中的对扩展开放准则。假设现在我们增加了一种自行车出行的方式。只需新增一个类即可。

  1. public class BikeStrategy implements Strategy{
  2. @Override
  3. public void travel() {
  4. System.out.println("bike");
  5. }
  6. }

之后设置策略即可

  1. public class Main {
  2. public static void main(String[] args) {
  3. TravelContext travelContext=new TravelContext();
  4. travelContext.setStrategy(new BikeStrategy());
  5. travelContext.travel();
  6. }
  7. }

而在Android的系统源码中,策略模式也是应用的相当广泛的.最典型的就是属性动画中的应用.

我们知道,在属性动画中,有一个东西叫做插值器,它的作用就是根据时间流逝的百分比来来计算出当前属性值改变的百分比.

我们使用属性动画的时候,可以通过set方法对插值器进行设置.可以看到内部维持了一个时间插值器的引用,并设置了getter和setter方法,默认情况下是先加速后减速的插值器,set方法如果传入的是null,则是线性插值器。而时间插值器TimeInterpolator是个接口,有一个接口继承了该接口,就是Interpolator这个接口,其作用是为了保持兼容

  1. private static final TimeInterpolator sDefaultInterpolator =
  2. new AccelerateDecelerateInterpolator();
  3. private TimeInterpolator mInterpolator = sDefaultInterpolator;
  4. @Override
  5. public void setInterpolator(TimeInterpolator value) {
  6. if (value != null) {
  7. mInterpolator = value;
  8. } else {
  9. mInterpolator = new LinearInterpolator();
  10. }
  11. }
  12. @Override
  13. public TimeInterpolator getInterpolator() {
  14. return mInterpolator;
  15. }
  1. public interface Interpolator extends TimeInterpolator {
  2. // A new interface, TimeInterpolator, was introduced for the new android.animation
  3. // package. This older Interpolator interface extends TimeInterpolator so that users of
  4. // the new Animator-based animations can use either the old Interpolator implementations or
  5. // new classes that implement TimeInterpolator directly.
  6. }

此外还有一个BaseInterpolator插值器实现了Interpolator接口,并且是一个抽象类

  1. abstract public class BaseInterpolator implements Interpolator {
  2. private int mChangingConfiguration;
  3. /**
  4. * @hide
  5. */
  6. public int getChangingConfiguration() {
  7. return mChangingConfiguration;
  8. }
  9. /**
  10. * @hide
  11. */
  12. void setChangingConfiguration(int changingConfiguration) {
  13. mChangingConfiguration = changingConfiguration;
  14. }
  15. }

平时我们使用的时候,通过设置不同的插值器,实现不同的动画速率变换效果,比如线性变换,回弹,自由落体等等。这些都是插值器接口的具体实现,也就是具体的插值器策略。我们略微来看几个策略。

  1. public class LinearInterpolator extends BaseInterpolator implements NativeInterpolatorFactory {
  2. public LinearInterpolator() {
  3. }
  4. public LinearInterpolator(Context context, AttributeSet attrs) {
  5. }
  6. public float getInterpolation(float input) {
  7. return input;
  8. }
  9. /** @hide */
  10. @Override
  11. public long createNativeInterpolator() {
  12. return NativeInterpolatorFactoryHelper.createLinearInterpolator();
  13. }
  14. }
  1. public class AccelerateDecelerateInterpolator extends BaseInterpolator
  2. implements NativeInterpolatorFactory {
  3. public AccelerateDecelerateInterpolator() {
  4. }
  5. @SuppressWarnings({"UnusedDeclaration"})
  6. public AccelerateDecelerateInterpolator(Context context, AttributeSet attrs) {
  7. }
  8. public float getInterpolation(float input) {
  9. return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
  10. }
  11. /** @hide */
  12. @Override
  13. public long createNativeInterpolator() {
  14. return NativeInterpolatorFactoryHelper.createAccelerateDecelerateInterpolator();
  15. }
  16. }

内部使用的时候直接调用getInterpolation方法就可以返回对应的值了,也就是属性值改变的百分比。

Android开发中常见的设计模式(四)——策略模式的更多相关文章

  1. Android开发中常见的设计模式 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  2. Android开发中无处不在的设计模式——动态代理模式

    继续更新设计模式系列.写这个模式的主要原因是近期看到了动态代理的代码. 先来回想一下前5个模式: - Android开发中无处不在的设计模式--单例模式 - Android开发中无处不在的设计模式-- ...

  3. Android开发中常见的设计模式

    对于开发人员来说,设计模式有时候就是一道坎,但是设计模式又非常有用,过了这道坎,它可以让你水平提高一个档次.而在android开发中,必要的了解一些设计模式又是非常有必要的.对于想系统的学习设计模式的 ...

  4. Android开发中常见的设计模式(二)——Builder模式

    了解了单例模式,接下来介绍另一个常见的模式--Builder模式. 那么什么是Builder模式呢.通过搜索,会发现大部分网上的定义都是 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建 ...

  5. Android开发中常见的设计模式(一)——单例模式

    首先了解一些单例模式的概念. 确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例. 这样做有以下几个优点 对于那些比较耗内存的类,只实例化一次可以大大提高性能,尤其是在移动开发中. 保持 ...

  6. Android开发中常见的设计模式(三)——观察者模式

    先看下这个模式的定义. 定义对象间的一种一对多的依赖关系,当一个对象的状态发送改变时,所有依赖于它的对象都能得到通知并被自动更新 先来讲几个情景. 情景1:有一种短信服务,比如天气预报服务,一旦你订阅 ...

  7. Android开发中常用的设计模式

    首先需要说明的是,这篇博文灵感来自于 http://www.cnblogs.com/qianxudetianxia/archive/2011/07/29/2121547.html ,在这里,博主已经很 ...

  8. Android 开发中常见的注意点

    这里总结了Android开发中常用的注意点.只有总结,没有展开举例讲解,展开的话,一个点都可以写一篇文章了..... 这类问题都一定不要犯. 重要的事情说三遍!!! 说三遍!!! 遍!!! 资源 不允 ...

  9. iOS 开发中常见的设计模式

    最近有小伙伴问到在iOS开发中的几种设计模式,这里摘录一下别人的总结(因为已经感觉总结得差不多了,适用的可以阅读一下) 首先是开发中的23中设计模式分为三大类:1.创建型 2.结构型 3.行为型 (i ...

随机推荐

  1. OpenStack的HA方案

    一.HA服务分类 HA将服务分为两类: 有状态服务:后续对服务的请求依赖之前对服务的请求,OpenStack中有状态的服务包括MySQL数据库和AMQP消息队列.对于有状态类服务的HA,如neutro ...

  2. linux 服务发布脚本升级,远程发布,指定拉取远程dev,test等分支代码

    1.本地发布脚本 publish.sh #!/bin/sh currentDay=`date +%Y%m%d` currentTime=`date +%Y%m%d%H%M%S` tomcat1=/da ...

  3. 【leetcode】448. Find All Numbers Disappeared in an Array

    problem 448. Find All Numbers Disappeared in an Array solution: class Solution { public: vector<i ...

  4. 【软件安装】nvidia驱动安装事宜

    https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html https://docs.nvidia.com/cuda/arch ...

  5. 快速排序的两种实现 -- 种轴partition : 比值partition(更精巧)

    实现1:种轴partition,not in place--取定枢轴,将小于等于枢轴的放到枢轴左边,大于枢轴的放到右边 # python algorithm en_2nd edition p125de ...

  6. QT4.8.6-VS2010开发环境配置

    目录 1.下载软件 2.环境配置 3.VAssistX配置 1.下载软件 VS2010下载地址:链接: https://pan.baidu.com/s/1gvPjZWBtSEwW37H1xf2vbA ...

  7. 【SpringBoot】SpringBoot拦截器实战和 Servlet3.0自定义Filter、Listener

    =================6.SpringBoot拦截器实战和 Servlet3.0自定义Filter.Listener ============ 1.深入SpringBoot2.x过滤器Fi ...

  8. H3C交换机限制子网之间的相互访问

    acl number 3000     rule 1 permit ip source 10.0.5.0 0.0.0.255 destination 172.16.1.100 0   #允许10.0. ...

  9. linux下一些重要命令的了解

    linux下一些比较重要的命令: du命令: 查看使用空间: 格式: du [选项][文件] 参数: -a  显示目录中个别文件的大小. -b  显示目录或文件大小时,以byte为单位. -c  除了 ...

  10. bootstrap modal 移除数据

    有时业务需求,在弹出模态框时需要动态的展示,但是不做处理时,每次弹出的都是第一次的数据,所以需要监听模态框关闭,每次关闭需要先清除里面的数据. //监听弹页关闭 $("#myModal&qu ...