1 介紹
Strategy模式是行為模式的一種,主要是對一系列算法的封裝,為所有算法定義一個抽象的算法接口,并通過繼承抽象算法接口對所有的算法加以封裝和實(shí)現(xiàn),而具體的算法調(diào)用交給用戶。

那么問題來了,作為一個學(xué)生,我們每天都要上課,上課的地點(diǎn)都在同一個教室,但是課本卻不是同一本。上課了,我們要怎么選擇課本呢?
2 實(shí)現(xiàn)方式
2.1 傳統(tǒng)方式
<!--核心代碼--!>
public String lesson(String course){
if("英語".equals(course)){
return "英語課本";
}else if("數(shù)學(xué)".equals(course)){
return "數(shù)學(xué)課本";
}else if("語文".equals(course)){
return "語文課本";
}else if("思政".equals(course)){
return "思政課本";
}
return null;
}
當(dāng)課程每增加一門,我們都需要追加一個if...else...,這樣使的整個程序代碼過于累贅,邏輯也變的復(fù)雜化,增加了開發(fā)人員的維護(hù)成本。
2.2 策略模式
策略模式的幾個角色:
- Strategy:策略抽象
- ConcreteStrategy : 各種策略的具體實(shí)現(xiàn)
- Context:策略的外部封裝類,根據(jù)不同的策略執(zhí)行不同的方法。

實(shí)現(xiàn)方式:
策略抽象:Strategy.class
public interface Strategy {
public void lesson();
}
策略具體實(shí)現(xiàn):MathStrategy.class / EnglishStrategy.class
public class MathStrategy implements Strategy{
@Override
public void lesson() {
System.out.println("數(shù)學(xué)課本");
}
}
public class EnglishStrategy implements Strategy{
@Override
public void lesson() {
System.out.println("英語課本");
}
}
外部封裝類:Context.class
public class Context implements Strategy{
private Strategy strategy;
<!--傳入一個具體的策略實(shí)現(xiàn)--!>
public Context(Strategy strategy) {
this.strategy = strategy;
}
@Override
public void lesson() {
this.strategy.lesson();
}
}
MainClass.class
public class MainClass {
public static void main(String[] args) {
<!--創(chuàng)建需要使用的策略對象--!>
Strategy strategy = new Context(new MathStrategy());
strategy.lesson();
}
}
當(dāng)我們需要添加一個新的課程實(shí)現(xiàn)(具體策略)時,我們只需要編寫一個子類實(shí)現(xiàn)Strategy并編寫具體的實(shí)現(xiàn)方法即可,這樣使得每個具體策略都獨(dú)立起來,相互之間不存在依賴關(guān)系,整個程序結(jié)構(gòu)也變的更加靈活,具有更好的維護(hù)性和拓展性,使開發(fā)人員可以更好的組織、調(diào)用。
3 優(yōu)缺點(diǎn)
優(yōu)點(diǎn)
- 使用策略模式可以避免多次的使用
if...else...的多重判斷語句,多重判斷語句不利于后期的維護(hù)和拓展。 - 策略模式將公共的代碼都轉(zhuǎn)移到父類中,從而省去了大量的重復(fù)代碼。
缺點(diǎn)
- 用戶必須知道所有的策略類,并自行去選擇適合的算法或行為。
喜歡的話戳一下喜歡唄。