策略模式定義了一組算法,將每個算法封裝起來,並使它們之間可以互相替換。這種模式讓算法的變化不會影響到使用算法的客戶端,實現了「開閉原則」——對擴展開放,對修改關閉。
以網購下單為例,用戶可選擇微信支付、支付寶、網銀等多種支付方式。這裡的「支付方式」就是一組可互換的算法。我們通過定義統一介面,將具體支付邏輯封裝在不同實現類中,實現運行時動態切換。
/**
* 支付策略介面
*/
public interface PayStrategy {
/** 支付方法 */
void pay();
}
微信支付:
/**
* 微信支付方式
*/
public class WeiXinPayStrategy implements PayStrategy {
public void pay() {
System.out.println("正在使用微信支付方式...");
}
}
支付寶支付:
/**
* 支付寶支付方式
*/
public class AlipayStrategy implements PayStrategy {
public void pay() {
System.out.println("正在使用支付寶支付方式...");
}
}
網銀支付:
/**
* 網銀支付方式
*/
public class CyberBankPayStrategy implements PayStrategy {
public void pay() {
System.out.println("正在使用網銀支付方式...");
}
}
public class Custom {
public void buy() {
System.out.println("已購買一雙襪子,準備去支付...");
}
/** 支持多種支付方式 */
public void pay(PayStrategy payStrategy) {
payStrategy.pay();
}
}
public class Client {
public static void main(String[] args) {
Custom custom = new Custom();
custom.buy();
// 此處可靈活切換支付方式
PayStrategy weixinPay = new WeiXinPayStrategy();
custom.pay(weixinPay);
}
}
已購買一雙襪子,準備去支付... 正在使用微信支付方式...
當系統需要在不同條件下採取不同行為,且這些行為邏輯相對獨立、可互換時,策略模式是理想選擇。常見於:支付系統、排序算法切換、壓縮格式選擇、路由算法選擇等場景。