10、Strategy 策略模式 整體地替換演算法 行為型模式
阿新 • • 發佈:2020-08-06
1、模式說明
策略模式比較好理解,就是將程序中用到的算法整體的拿出來,並有多個不同版本的算法實現,在程序運行階段,動態的決定使用哪個算法來解決問題。
2、舉例
排序算法的問題,假如我們的程序中需要對數據進行排序,我們知道,不同的算法具有不同的時間復雜度和空間復雜度,因此需要在程序運行時,根據可用內存和數據特徵,選用不同的算法(排序策略),這就是策略模式的使用場景之一。再舉個例子,負載均衡算法:如果某個服務部署了多個冗餘的實例,客戶端在向服務端發送請求時,根據負載均衡算法策略,請求可能會被轉發到不同的服務提供者實例來處理,如何決定某個請求轉發給哪個服務實例呢,最簡單的做法就是輪詢,順次將請求轉發給每個服務實例進行處理。也可以採用隨機方式,或者根