定義
策略模式定義了一系列的算法,并將每一個(gè)算法封裝起來,而且使它們還可以相互替換。策略模式讓算法獨(dú)立于使用它的客戶而獨(dú)立變化。
使用場景
- 針對同一類型問題的多種處理方式,僅僅是具體行為有差別時(shí)。
- 需要安全地封裝多種同一類型的操作時(shí)。
- 出現(xiàn)同一抽象類有多個(gè)子類,而又需要時(shí)if-else或者switch-case類選擇具體子類時(shí)。
uml圖

策略模式uml
- Context:用來操作策略的上下文環(huán)境。
- Starategy:策略的抽象。
- Concreate StrategyA、Concreate StrategyB:具體策略實(shí)現(xiàn)。
具體代碼
以為對價(jià)格進(jìn)行處理為例。對價(jià)格進(jìn)行取整,策略一:四舍五入。策略二:抹去所有小數(shù)。
//策略的接口
interface PriceStrategy {
int calPrice(double price);
}
//具體的不同策略
//四舍五入
class RoundPrice implements PriceStrategy {
@Override
public int calPrice(double price) {
if (price < 0) {
throw new IllegalArgumentException("價(jià)格不能為負(fù)");
}
if (price == 0d) {
return 0;
} else {
return (int) (price + 0.5);
}
}
}
//取整
class ArrangementPrice implements PriceStrategy {
@Override
public int calPrice(double price) {
if (price < 0) {
throw new IllegalArgumentException("價(jià)格不能為負(fù)");
}
return (int) price;
}
}
首先,確定統(tǒng)一的調(diào)用規(guī)范,通過calPrice方法獲取最后的數(shù)據(jù),再創(chuàng)建具體的策略實(shí)現(xiàn)類:RoundPrice、ArrangementPrice。
//策略的使用場景
class PriceCal {
private PriceStrategy strategy = new RoundPrice();
private double realPrice;
public PriceCal(double realPrice) {
this.realPrice = realPrice;
}
public PriceStrategy getStrategy() {
return strategy;
}
public void setStrategy(PriceStrategy strategy) {
this.strategy = strategy;
}
public int getPaidPrice() {
return strategy.calPrice(realPrice);
}
}
再實(shí)現(xiàn)策略的使用場景類。通過設(shè)置strategy屬性來使用不同的策略。
使用方式
public static void main(String[] args) {
PriceCal priceCal = new PriceCal(10.72);
//設(shè)置需要的策略
priceCal.setStrategy(new RoundPrice());
System.out.println(priceCal.getPaidPrice());
}
上面可以看出,策略模式在使用的優(yōu)勢。具體的策略實(shí)現(xiàn)已經(jīng)和策略的使用場景相分離。當(dāng)需要添加新的策略時(shí),只需要實(shí)現(xiàn)接口,再在使用時(shí)添加就可以。而if-else的方法這需要修改使用場景類,來解決這個(gè)問題。