67.设计模式笔记-策略模式

来源:互联网 发布:量子计算机和人工智能 编辑:程序博客网 时间:2024/05/18 14:14

转载请注明出处 http://blog.csdn.net/qq_31715429/article/details/78435769
本文出自:猴菇先生的博客

1.定义
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们可以在不同场景下相互替换。

2.使用场景
(1)针对同一类型问题的多种处理方式,仅仅是具体行为有差别时。
(2)需要安全的封装多种同一类型的操作时。
(3)出现同一抽象类有多个子类,而又需要使用if-else或者switch-case来选择具体子类时。

3.例子
在Android中差值器Interpolator就是一个典型的策略模式,给动画设置差值器,只需要new不同类型的差值器对象。
下面模仿Interpolator写一个最简单的取值方法:

public class Interpolator{    public static final String LINEAR = "linear";    public static final String ACCELERATE = "accelerate";    private String mType;    public Interpolator(String type){        mType = type;    }    public float getInterpolation(float input){        float result = 0;        switch(mType){            case LINEAR:                result = getLinearInterpolation(input);                break;            case ACCELERATE:                result = getAccelerateInterpolation(input);                break;            default:                break;        }        return result;    }    /**     * 匀速     */    private float getLinearInterpolation(float input){        return input;    }    /**     * 加速     */    private float getAccelerateInterpolation(float input){        return input * input;    }}
public class Test{    public static void main(String[] args){        // Interpolator1 interpolator = new Interpolator1(Interpolator1.LINEAR);        Interpolator1 interpolator = new Interpolator1(Interpolator1.ACCELERATE);        for(int i = 0 ; i < 10 ; i++){            System.out.print(interpolator.getInterpolation(i) + " ");        }    }}

如果按以上的方式,如果再写减速、先加速在减速的类型,就需要再写case。这种简单的解决方案问题太多,例如耦合性太高、代码臃肿、难以维护等。而应对这种情况的策略模式就能很好地解决这类问题,它将各种方案分离开来,让程序客户端根据具体的需求来动态地选择不同的策略方案。

下面我们对上述示例用策略模式进行重构:

/** * 取值接口 */public interface Interpolator{    public float getInterpolation(float input);}
/** * 匀速取值策略 */public class LinearInterpolator implements Interpolator{    @Override    public float getInterpolation(float input){        return input;    }}
/** * 加速取值策略 */public class AccelerateInterpolator implements Interpolator{    @Override    public float getInterpolation(float input){        return input * input;    }}
public class Test{    public static void main(String[] args){        // LinearInterpolator interpolator = new LinearInterpolator();        AccelerateInterpolator interpolator = new AccelerateInterpolator();        for(int i = 0 ; i < 10 ; i++){            System.out.print(interpolator.getInterpolation(i) + " ");        }    }}

经过上述重构之后,去个了各种各样的switch-case语句,结构也变得清晰,可拓展性变得很强,例如,当我们需要增加减速取值策略时,只需要添加一个减速取值策略类即可:

/** * 减速取值策略 */public class DecelerateInterpolator implements Interpolator{    @Override    public float getInterpolation(float input){        return (float)Math.sqrt(input);    }}

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

优点
•结构清晰明了、使用简单直观;
•耦合度相对而言较低,扩展方便;
•操作封装也更为彻底,数据更为安全。

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

原创粉丝点击