一、定义
定义了一系列算法,并将每一个算法封装起来,而且他们之间可以相互切换
策略模式让算法独立于使用它的客户而独立变化。
二、角色
Context:用来操作策略的上下文环境。
Strategy:抽象策略类,定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,环境角色使用这个接口调用不同的算法,一般使用接口或抽象类实现
ConcreteStrategy:具体策略类:实现了抽象策略定义的接口,提供具体的算法实现
三、示例代码
抽象策略类
public interface Strategy {
void show();
}
定义具体策略角色
//具体策略A
public class StrategyA implements Strategy {
public void show() {
System.out.println("具体策略A");
}
}
//具体策略B
public class StrategyB implements Strategy {
public void show() {
System.out.println("具体策略B");
}
}
//具体策略C
public class StrategyC implements Strategy {
public void show() {
System.out.println("具体策略C");
}
}
定义环境角色
public class Context {
//持有抽象策略角色的引用
private Strategy strategy;
public SalesMan(Strategy strategy) {
this.strategy = strategy;
}
//向客户展示促销活动
public void contextShow(){
strategy.show();
}
}
Client
public static void main(String[] args) {
Context context = new Context(new StrategyA());
context.contextShow();
}
四、优缺点
优点:
结构清晰明了、使用简单直观,策略类之间可以自由切换
耦合度相对而言较低,扩展方便,新增一个策略只需要添加一个策略类,复合开闭原则
避免使用多重条件选择语句
缺点:
随着策略的增加,子类也会变得繁多。
五、使用场景
业务代码需要根据场景不同,切换不同的实现逻辑
代码中存在大量 if else 逻辑判断
六、在Android中的使用
属性动画:
时间插值器(TimeInterpolator)使用了策略模式。作用为根据时间的流逝的百分比计算当前属性值改变的百分比。
预设的有多种插值器,
LinearInterpolator 线性插值器:匀速动画
AccelerateDecelerateInterpolator 加速减速插值器:动画两头慢中间快
DecelerateInterpolator 减速插值器:动画越来越慢
三个类都实现了 Interpolator 接口,接口内部只有一个用来计算属性值的改变的百分比的 getInterpolation 方法需要实现。
估值器(TypeEvaluator)根据属性值改变的百分比来计算改变后的
系统预置的有3种:
IntEvaluator:针对整形属性
FloatEvaluator:针对浮点型属性
ArgbEvaluator:针对 Color 属性
自定义插值器和估值器:
七、使用案例
抽象策略类:交通工具选择方式 (TripMode)
具体策略类:Bytrian(坐火车),Bycar(坐汽车),Selfdrive(做自驾车)等
public class strategy {
public static void main(String[] args) {
TripMode tp = new Selfdrive();
WyTour mytour = new WyTour(tp);
mytour.Get_getout();
}
}
//不同交通工具都应有的方法
interface TripMode {
void getout();
}
//坐火车
class Bytrian implements TripMode{
@Override
public void getout() {
System.out.println("已选择交通工具,坐火车。");
}
}
//坐汽车
class Bycar implements TripMode{
@Override
public void getout() {
System.out.println("已选择交通工具,坐汽车。");
}
}
//坐自驾车
class Selfdrive implements TripMode{
@Override
public void getout() {
System.out.println("已选择交通工具,坐自驾车。");
}
}
//环境类
class WyTour {
private TripMode _stragety;
public WyTour(TripMode stragety){
_stragety = stragety;
}
public void Get_getout(){
_stragety.getout();
}
}