来聊聊我所学习的设计模式-策略模式
策略模式的介绍
引用官方的说法:策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。策略模式里面有三个角色:Context用来操作策略的上下文角色,Stragety策略的抽象,ConcreateStragetyA,ConcreateStragetyA具体的实现类 .
<p>看到这里可能有点抽象。别急,我们在这里引入一个小故事,周瑜赔了夫人又折兵听过了吧,是我们的诸葛亮给赵云3个锦囊妙计,让刘备可以取到老婆。三个锦囊妙计都是同一个东西,我们就定义一个接口:Stragety,里面是可执行的算法。锦囊1,锦囊2就是我们的具体实现类,而赵云就是我们用于操作策略的上下文角色。说到这里应该有所了解了吧。那么看一下代码究竟是如何实现的
首先我们先定义一个接口
public interface Strategy { //锦囊的接口
public void operation(); //每个锦囊妙计都是一个可执行的算法
}
再来写三个实现类
第一个实现类
public class FirstWay implements Strategy {
public void operation() {
System.out.println("找乔国老帮忙,让吴国太给孙权施加压力");
}}
第二个实现类
public class SecondWay implements Strategy {
@Override
public void operation() {
System.out.println("求吴国太开个绿灯,放行!");
}}
第三个实现类
public class ThirdWay implements Strategy {
@Override
public void operation() {
System.out.println("孙夫人断后,挡住追兵");
}}
再来写个Context
public class Context {
private Strategy stragety;
//决定赵云用的哪个锦囊
public Context(Strategy stragety){
this.stragety=stragety;
}
//使用锦囊
public void operation(){
stragety.operation();
}}
准备了这么多,是时候让赵云出场帮助刘备娶老婆了
public class Zhaoyun {
public static void main(String[] args) {
Context context;
context=new Context(new FirstWay());
context.operation(); //开始使用第一个锦囊
context=new Context(new SecondWay());
context.operation(); //使用第二个锦囊
context=new Context(new ThirdWay());
context.operation(); //使用第三个锦囊
}}
就这样,孙权这回真是赔了夫人又折兵
OK 讲完了基础和理论,下面讲一下实战的应用
我们知道在android动画中有两个重要的属性interpolator(插值器)和Evaluator(估值器)这里不重点介绍。主要看它们俩是如何实现策略模式的
先来看一下interpolator是如何实现的,直接贴关键的源码,所有的interpolator最终都实现了TimeInterpolator接口,而这个接口就相当于我们的Strategy
public interface TimeInterpolator {
float getInterpolation(float input); //每一个interpolator都到重写这个的方法
}
**举个简单的例子 LinearInterpolator,如果你的动画里面加入了这个,那么你的动画将会以常量速率改变,android也给了我们许多其他的interpolator,当然我们也可以自己重写,只要实现getInterpolation。LinearInterpolator和其他的interpolator就是我们的实现类,然后操作他们的英雄就是动画objectAnimator.setInterpolator(new LinearInterpolator()); **
Evaluator(估值器)它也是一个策略模式,请看它们的接口,其实用法跟上述的interpolator差不多,先看一个源码,再说作用
public interface TypeEvaluator<T> {
public T evaluate(float fraction, T startValue, T endValue);}
其中fraction就是加速器中的返回值,表示当前动画的数值进度,百分制的小数表示。 startValue和endValue分别对应ofInt(int start,int end)中的start和end的数值;
public class ScaleType implements TypeEvaluator<Integer> {
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
int startInt = startValue;
return (int)(200+startInt + fraction * (endValue - startInt)); }}
ValueAnimatoranimator=ValueAnimator.ofInt(0,200);
animator.setEvaluator(new ScaleType());
简单说一下这段代码的意义,本来我动画的区间就是(0,200),但是我的Evaluator增加了200,所以实际上区间成了(200,400)
这就是我对策论模式的学习,以及对它运用在android上。可能大家对运用在动画那里有些不懂,我的描述跟语言有点乱,不知道大家看懂策略模式没有。这毕竟第一次写文章,写的不好请多多见谅。
更多精彩文章请关注微信公众号"Android经验分享":这里将长期为您分享Android高手经验、中外开源项目、源码解析、框架设计和Android好文推荐!QQ交流群:Android经验分享一区 386067289