转载请注明出处:http://blog.youkuaiyun.com/binbinqq86/article/details/71023871
今天要讲解的是设计模式之——策略模式(Strategy)。理论概念性的东西先不讲,下面先上场景和案例:
小明所在的公司想要设计一款交通出行帮助系统,提供全方位的详细出行说明帮助,包含具体路线,花费,耗时等等。。。由于小明是公司主程,毫无疑问,主管把这个艰巨而光荣的任务交给了他,小明拍着胸脯告诉主管说:一个星期就可以搞定整套系统~
下面来看小明的核心代码:
package com.example.tb.myapplication;
/**
* Created by tb on 2017/5/1.
* 包括了(公交-0,地铁-1,火车-2,飞机-3,轮船-4,出租车-5,大巴车-6,轻轨-7,自驾-8)等等各种出行方式的出行帮助系统核心类
*/
public class Travel {
/**
* 花费
* @param line 具体路线
* @param trafficType 交通工具类型
* @return
*/
public float cost(int line,int trafficType){
float cost=0;
if(line==0&&trafficType==0){
//具体的计算方案
}else if(line==0&&trafficType==1){
//具体的计算方案
}else if(...){
//具体的计算方案
}...
//更多情况的计算方案...
return cost;
}
/**
* 耗时
* @param line 具体路线
* @param trafficType 交通工具类型
* @return
*/
public long time(int line,int trafficType){
long time=0;
switch (line){
case 0://路线0具体的计算方案
if(trafficType==0){
//具体的计算方案
}else if(trafficType==1){
//具体的计算方案
}else if(...){
//具体的计算方案
}
break;
case 1://路线1具体的计算方案
break;
case 2://路线2具体的计算方案
break;
//更多情况的计算方案...
}
return time;
}
}
很快,小明就把整个系统的核心功能做完了(我们这里采用伪代码来简要说明问题),可以看出光是路线跟花费就需要用到那么多的if…else,或者switch…case,甚至是两者嵌套才能实现具体的功能,当主管看到后,一脸嫌弃的说,小明啊,这代码可读性太差了,而且如果我以后增加了出行方式或者路线呢,你怎么办?而且随着功能增加,你的类会越来越庞大,在里面加东西很容易出错,这是非常不易于扩展和维护的啊。听完主管的话,小明就像放了气的气球,本来还想能得到一番表扬呢。最后主管让小明看一下设计模式中的策略模式,然后再去进行优化,小明顿时就像得到了高人指点,回去后赶紧翻阅资料,经过一段时间的研究后,终于有了一些眉目,连自己都看不下去自己写的这段代码了,下决心去重构。。。
上面就是小明设计的整个系统结构图(可以在新窗口中查看大图),其核心就是把路线跟交通工具这两个变化的因素独立出来,做成两个接口,这样在后续维护扩展的时候如果有新的路线或者交通工具出现,只需要添加对应的一个类去实现这两个接口就可以了,非常方便,而且整体代码不那么臃肿,Travel这个类只负责具体的计算,不再判断复杂的业务逻辑了,遵循了类的单一职责原则。
下面是伪代码:
package com.example.tb.myapplication.strategy;
/**
* Created by tb on 2017/5/1.
*/
public interface Line {
/**
* 路线规划图
*/
public int getLine();
}
package com.example.tb.myapplication.strategy;
/**
* Created by tb on 2017/5/1.
*/
public interface Traffic {
/**
* 交通工具类型
*/
public int getTrafficType();
}
package com.example.tb.myapplication.strategy;
/**
* Created by tb on 2017/5/1.
*/
public class Line0 implements Line{
@Override
public int line() {
return 0;
}
}
package com.example.tb.myapplication.strategy;
/**
* Created by tb on 2017/5/1.
*/
public class BusTravel implements Traffic{
@Override
public int trafficType() {
return 0;
}
}
package com.example.tb.myapplication.strategy;
/**
* Created by tb on 2017/5/1.
* 包括了(公交-0,地铁-1,火车-2,飞机-3,轮船-4,出租车-5,大巴车-6,轻轨-7,自驾-8)等等各种出行方式的出行帮助系统核心类
*/
public class Travel {
private Line line;
private Traffic traffic;
private int realLine,realTraffic;
public void Travel(Line line,Traffic traffic){
this.line=line;
this.traffic=traffic;
realLine=line.getLine();
realTraffic=traffic.getTrafficType();
}
public void setLine(Line line) {
this.line = line;
}
public void setTraffic(Traffic traffic) {
this.traffic = traffic;
}
/**
* 花费
* @return
*/
public float cost(){
//根据路线和交通工具去计算具体的花费。。。
return 0;
}
/**
* 耗时
* @return
*/
public long time(){
//根据路线和交通工具去计算具体的花费。。。
return 0;
}
}
package com.example.tb.myapplication.strategy;
import android.util.Log;
/**
* Created by tb on 2017/5/1.
*/
public class Test {
private static final String TAG = "Test";
public void test(){
Line line=new Line0();
Traffic traffic=new BusTravel();
Travel travel=new Travel();
travel.setLine(line);
travel.setTraffic(traffic);
Log.d(TAG, "test: cost is:"+travel.cost()+"\ntime is:"+travel.time());
}
}
由于篇幅问题,这里我只列举了Line0,BusTraffic这两个子类,具体测试在Test类中,可以通过Travel对象的两个set方法进行依赖注入,动态的去改变计算结果。这次小明完成后给主管看了看,得到了主管的夸赞,小明心里乐出了花~~~
这就是策略模式的强大,核心就是定义了算法族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。这个模式很完美的展示了抽象的魅力,注入不同的实现,从而达到很好的可扩展性,同时这也是系统优化的一个很重要方法:从模式谈论软件系统,可以让你保持在设计层次,不会被压低到对象与类这种琐碎的事情上面。
策略模式的优缺点如下:
- 优点:
- 结构清晰明了,使用简单直观
- 耦合度相对而言较低,扩展方便
- 操作封装也更为彻底,数据更为安全
- 缺点
- 随着策略的增加,子类也会变的繁多
策略模式在Android系统源码中的应用:Interpolator。这个类主要是在做动画的时候会涉及到,但是都是它的子类,比如:LinearInterpolator、CycleInterpolator等动画插值器就是具体的实现策略,通过注入不同的插值器实现不同的动态效果(匀速、加速、减速等),这个类是从TimeInterpolator接口实现而来,里面只有一个方法:
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.animation;
/**
* A time interpolator defines the rate of change of an animation. This allows animations
* to have non-linear motion, such as acceleration and deceleration.
*/
public interface TimeInterpolator {
/**
* Maps a value representing the elapsed fraction of an animation to a value that represents
* the interpolated fraction. This interpolated value is then multiplied by the change in
* value of an animation to derive the animated value at the current elapsed animation time.
*
* @param input A value between 0 and 1.0 indicating our current point
* in the animation where 0 represents the start and 1.0 represents
* the end
* @return The interpolation value. This value can be more than 1.0 for
* interpolators which overshoot their targets, or less than 0 for
* interpolators that undershoot their targets.
*/
float getInterpolation(float input);
}
可以看出getInterpolation返回的就是动画的流逝时间百分比,具体实现交给子类,进而完成千变万化的动画效果。
怎么样,策略模式就讲完了,简单吧~如果有不明白的童鞋请在下方留言。。。
1858





