Java設計模式10: 策略模式
阿新 • • 發佈:2018-11-07
一、什麼是策略模式?
策略模式屬於物件的行為模式。其用意是針對一組演算法,將每一個演算法封裝到具有共同介面的獨立的類中,從而使得它們可以相互替換。策略模式使得演算法可以在不影響到客戶端的情況下發生變化。
策略模式把一個系列的演算法封裝到一個系列的具體策略類裡面,作為一個抽象策略類的子類或策略介面的實現類。簡單地說:準備一組演算法,並將每一個演算法封裝起來,使它們可以互換。
這個模式涉及到3個角色:
環境(Context)角色:持有一個Strategy抽象策略類或策略介面的引用。
抽象策略(Strategy)角色:這是一個抽象角色,由一個介面或抽象類實現。此角色宣告所有的具體策略類需要重寫的方法。
具體策略(Concrete Strategy)角色:封裝了相關的演算法或行為。
二、直接上程式碼示例:
這樣一個場景:某線上超市初級會員不打折,中級會員打8折,高階會員打5折
先建立一個策略模式介面:
/** * <pre> * @author : orange * @e-mail : [email protected] * @time : 2018/10/17 18:12 * @desc : 策略模式抽象介面 * @version: 1.0 * </pre> */ public interface MemberStrategy { Double calculationPrice(Double price); }
再分別建立策略介面的實現類:
初級會員實現類
/** * <pre> * @author : orange * @e-mail : [email protected] * @time : 2018/10/17 18:18 * @desc : * @version: 1.0 * </pre> */ public class JuniorMemberStrategy implements MemberStrategy { @Override public Double calculationPrice(Double price) { System.out.println("初級會員不打折扣"); return null; } }
中級會員實現類
/**
* <pre>
* @author : orange
* @e-mail : [email protected]
* @time : 2018/10/17 18:44
* @desc :
* @version: 1.0
* </pre>
*/
public class IntermediateMemberStrategy implements MemberStrategy{
@Override
public Double calculationPrice(Double price) {
System.out.println("中級會員打8折");
return price * 0.8;
}
}
高階會員實現類
/**
* <pre>
* @author : orange
* @e-mail : [email protected]
* @time : 2018/10/17 19:18
* @desc :
* @version: 1.0
* </pre>
*/
public class SeniorMemberStrategy implements MemberStrategy {
@Override
public Double calculationPrice(Double price) {
System.out.println("高階會員打折腿。");
return price * 0.5;
}
}
價格類
/**
* <pre>
* @author : orange
* @e-mail : [email protected]
* @time : 2018/10/17 19:26
* @desc :
* @version: 1.0
* </pre>
*/
public class Price {
private MemberStrategy memberStrategy;
public Price(MemberStrategy memberStrategy){
this.memberStrategy = memberStrategy;
}
public Double calPrice(Double price){
return memberStrategy.calculationPrice(price);
}
}
客戶端測試
/**
* <pre>
* @author : orange
* @e-mail : [email protected]
* @time : 2018/10/17 19:29
* @desc : 客戶端測試
* @version: 1.0
* </pre>
*/
public class Client {
public static void main(String[] args) {
SeniorMemberStrategy seniorMemberStrategy = new SeniorMemberStrategy();
Price price = new Price(seniorMemberStrategy);
Double calPrice = price.calPrice(100D);
System.out.println("calPrice:" + calPrice);
}
}
總結:
策略模式優點:
1 通過策略類的等級結構來管理演算法族。
2 避免使用將採用哪個演算法的選擇與演算法本身的實現混合在一起的多重條件(if-else if-else)語句。
策略模式缺點:
1 客戶端必須知道所有的策略類,並自行決定使用哪一個策略類。
2 由於策略模式把每個演算法的具體實現都單獨封裝成類,針對不同的情況生成的物件就會變得很多。