您的位置:首页 > 其它

设计模式-策略模式

2016-03-28 21:13 393 查看

1.策略模式介绍

在软件开发过程中经常遇见这样的问题:实现某一个功能可以有多种算法或者策略,我们根据实际情况选择不同的算法或者策略来完成此功能。例如,排序算法,可以使用插入排序、归并排序、冒泡排序等。
如果将这些算法或者策略抽象出来,提供一个统一的接口不同的算法或者策略有不同的实现类,这样程序客户端就可以通过注入不同的实现对象来实现算法或者策略的动态替换,这种模式的可扩展性、可维护性也就很高。

2.策略模式的定义

策略模式定义了一系列的算法,并将每一个算法封装起来,而且使他们还可以相互替换。策略模式让算

法独立于使用它的客户而独立变换

3.策略模式的使用场景

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

4.UML类图



5.代码实现

例如交通工具的计算方法,公交车分段计算,10公里以内1元,超过10公里以后每加一元可多乘5公里。地铁分段计算,6公里以内3元,6-12公里(含)4元,13-22公里(含)5元,23-32公里(含)6元,其它7元。出租车每公里2元。
1.策略抽象

/**
* 计算接口
* Created by Teaphy
* 2016/3/28.
*/
public interface CalculateStrategy {

/**
* 按距离来计算价格
* @param km 公里数
* @return 价格
*/
int  calculatePrice(int km);
}

2.具体的策略实现

/**
* 公交车价格结算
* Created by Teaphy
* 2016/3/28.
*/
public class BusStrategy implements CalculateStrategy {

/**
* 公交车分段计算,10公里以内1元,超过10公里以后每加一元可多乘5公里
* @param km 公里数
* @return
*/
public int calculatePrice(int km) {
if (km < 10) {
return 1;
}
// 超过10公里的总距离
int extraTotal = km -10;
// 超过的距离是5公里的倍数
int extraFactor = extraTotal / 5;
// 超过的距离对5公里的余数
int fraction = extraTotal % 5;
// 价格计算
int price = 1 + extraFactor * 5;

return fraction > 0 ? ++price : price;
}
}

/**
* 地铁价格结算
* Created by Teaphy
* 2016/3/28.
*/
public class SubwayStrategy implements CalculateStrategy {

/**
* 地铁分段计算,6公里以内3元,6-12公里(含)4元,13-22公里(含)5元,23-32公里(含)6元
* @param km 公里数
* @return
*/
public int calculatePrice(int km) {
if (km < 6) {
return 3;
} else if (km > 6 && km <= 12) {
return 4;
} else if (km > 12 && km <= 22) {
return 5;
} else if (km > 22 && km <= 32) {
return 6;
}
return 7;
}
}

/**
* 出租车价格计算
* Created by Teaphy
* 2016/3/28.
*/
public class TexStrategy  implements CalculateStrategy{

/**
* 出租车每公里2元
* @param km 公里数
* @return
*/
public int calculatePrice(int km) {

return 2 * km;
}
}

3.策略设置对象

/**
* 价格计算 - 策略设置类
* Created by Teaphy
* 2016/3/28.
*/
public class TranficCalculator {
CalculateStrategy mCalculateStrategy;

public void setmCalculateStrategy(CalculateStrategy mCalculateStrategy) {
this.mCalculateStrategy = mCalculateStrategy;
}

public int calculatePrice(int km) {
return mCalculateStrategy.calculatePrice(km);
}
}

5. 测试类

/**
* Created by Teaphy
* 2016/3/28.
*/
public class TestStrategy {
public static void main(String[] args) {
TranficCalculator tc = new TranficCalculator();

tc.setmCalculateStrategy(new BusStrategy());
System.out.println("Bus: " +  tc.calculatePrice(16));

tc.setmCalculateStrategy(new SubwayStrategy());
System.out.println("Subway: " +  tc.calculatePrice(16));

tc.setmCalculateStrategy(new TexStrategy());
System.out.println("Tex: " +  tc.calculatePrice(16));
}
}

6. 输出结果
Bus: 7
Subway: 5
Tex: 32

6.总结

策略模式用于分离算法,在相同的行为抽象下游不同的具体实现策略,这个模式

很好的展示了开闭原则,也就是定义抽象,注入不同的实现,从而达到很好的扩展效果

优点

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

缺点

* 随着策略的增加,子类也会变的繁多;

参考资料:

1.Android源码分析与设计模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: