概述
策略模式定义了一系列的算法,把每个算法封装起来,它们之间可以相互替换。相当于给客户端提供了一系列的策略,让客户端根据不同的场景,调用不同的策略。避免了使用多重条件选择语句,解耦,增加一个策略,只需要增加一个策略类即可,不需要修改原有的代码,符合设计模式中的开放封闭原则(对扩展开放,对修改封闭)。策略模式属于行为型设计模式。
策略模式的实现
我们以回家的交通方式为例,简单介绍下策略模式的实现,回家的交通方式,我们可以选择做汽车、火车、飞机。根据每个人的情况不同,不同的人的会选择不同的交通出行方式。离家近的可能选择做汽车、较远的可能选择火车出行、再远一点可能选择飞机出行。
(1)创建抽象策略类
/**
* 抽象策略类
*/
public abstract class AbstractStrategy {
protected void goHome(){};
}
(2)创建具体策略类
/**
* 具体策略类
*/
public class Bus extends AbstractStrategy {
@Override
protected void goHome() {
Log.e("======","坐汽车回家");
}
}
/**
* 具体策略类
*/
public class Train extends AbstractStrategy {
@Override
protected void goHome() {
Log.e("======","坐火车回家");
}
}
/**
* 具体策略类
*/
public class Plane extends AbstractStrategy {
@Override
protected void goHome() {
Log.e("======","坐飞机回家");
}
}
(3)创建策略环境类
/**
* 策略环境类
*/
public class ContextStrategy {
private AbstractStrategy strategy;
public ContextStrategy(AbstractStrategy strategy){
this.strategy=strategy;
}
public void goHome(){
strategy.goHome();
}
}
测试
/**
* 策略模式
*/
private void testStrategy(){
Bus bus=new Bus();
ContextStrategy contextStrategy=new ContextStrategy(bus);
contextStrategy.goHome();
}
输出结果:
2020-03-23 15:13:44.318 16879-16879/com.she.javaprojectdemo E/======: 坐汽车回家
总结
策略模式解耦,隐藏了算法的实现。如果一个类拥有很多行为,而又需要使用if-else或者switch语句来选择具体行为时。使用策略模式把这些行为独立到具体的策略类中,可以避免多重选择的结构。
如我们常使用的ListView的setAdapter,可以根据不同的场景使用ListAdapter、ArrayAdapter等运用到了策略模式。以及动画中的插值器(ValueAnimator 的 setInterpolator 方法)也是有运用到策略模式。