策略模式之一

策略模式(Strategy):它定義了一系列的算法,並將每個算法封裝起來,並且使它們還能夠相互替換。策略模式讓算法的變化不會影響到使用算法的客戶。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)

 

 咱們如今假定一種場景:算法

規則以下,若是時間大於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;

/**
* 一個上班族的出行選擇
*
* @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);

}

}
能夠看到,client只和策略選擇器合做,因此之後若是有新的算法出現,只要實現出行接口,修改策略選擇器就能夠了,客戶端代碼沒必要作任何修改,比if-else是否是看的更舒服點呢!
相關文章
相關標籤/搜索