咱們如今假定一種場景:算法
規則以下,若是時間大於60分鐘,選擇步行,30-60分鐘,選擇騎車,10-30分鐘,選擇巴士,小於10分鐘,就不出門了。ide
若是不用模式的話,咱們能夠用if else的方式在客戶端的代碼中填上咱們的規則,可是這樣的壞處是若是之後時間被繼續細化,出行方式更多的話,那客戶端就要不斷的修改代碼。而後須要從新測試過每一種可能。策略模式最大的好處是算法的改變不影響客戶端的調用。客戶端直接與算法調度器合做,算法調度器根據條件選擇適合的算法。而後再執行,下面是個例子。測試
package com.spell.designPattern.strategy;自行車方式上班……
/**
* 出行策略接口,出行的方式有步行、跑步、自行車、公交車、自駕車等
*
* @author Administrator
*
*/
public interface ArriveStrategy {
/**
* 抵達方式
*/
public void howToArrive();
}
package com.spell.designPattern.strategy;巴士出行
/**
* 出行方式:自行車
*
* @author Administrator
*
*/
public class ArriveStrategyBike implements ArriveStrategy {
public void howToArrive() {
System.out.println("騎車出行,速度是15km/h");
}
}
package com.spell.designPattern.strategy;走路的方式
public class ArriveStrategyBus implements ArriveStrategy {
public void howToArrive() {
System.out.println("公交車出行,速度是40km/h");
}
}
package com.spell.designPattern.strategy;根據時間,選擇合適的出行方式:
public class ArriveStrategyWalk implements ArriveStrategy {
public void howToArrive() {
System.out.println("步行,速度是3KM/H");
}
}
package com.spell.designPattern.strategy;偶的上班選擇……
/**
* 出行策略選擇,根據剩餘的時間來選擇某種方式
*
* @author Administrator
*
*/
public class StrategySelector {
/**
* 根據時間來選擇對應的策略
*
* @param time
* @return
*/
public ArriveStrategy get(int time) {
if (time >= 60) {
// 有足夠的時間,就走路過去
return new ArriveStrategyWalk();
} else if (time >= 30) {
// 時間還有點,騎自行車就能夠解決
return new ArriveStrategyBike();
} else if (time >= 10) {
// 時間很少了,公交車會更快點
return new ArriveStrategyBus();
} else {
// 怎麼都來不及了,仍是請假吧
return null;
}
}
}
package com.spell.designPattern.strategy;能夠看到,client只和策略選擇器合做,因此之後若是有新的算法出現,只要實現出行接口,修改策略選擇器就能夠了,客戶端代碼沒必要作任何修改,比if-else是否是看的更舒服點呢!
/**
* 一個上班族的出行選擇
*
* @author Administrator
*
*/
public class Client {
private StrategySelector selector = new StrategySelector();
/**
* 去公司上班,出行方式根據剩下的時間來選擇
*
* @param time
*/
public void toCompany(int time) {
ArriveStrategy strategy = selector.get(time);
if (strategy != null) {
strategy.howToArrive();
} else {
System.out.println("怎麼也來不及了,打請假電話中……");
}
}
public static void main(String[] args) {
Client client = new Client();
client.toCompany(60);
client.toCompany(40);
client.toCompany(15);
client.toCompany(5);
}
}