在策略模式中,一個類的行爲或算法能夠在運行時動態更改。算法
GOF對策略模式的描述爲:
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients.
— Design Patterns : Elements of Reusable Object-Oriented Softwarethis
UML類圖以下:
3d
策略模式包含三個角色:code
代碼示例:
以電商會員折扣爲例,不一樣級別的會員享受的折扣是不一樣的,這種差別能夠用策略模式來封裝。對象
public interface Strategy { double CalcPrice(double originalPrice); } public class PrimaryStrategy : Strategy { public double CalcPrice(double originalPrice) { return originalPrice; } } public class IntermediateStrategy : Strategy { public double CalcPrice(double originalPrice) { return originalPrice * 0.9; } } public class AdvancedStrategy : Strategy { public double CalcPrice(double originalPrice) { return originalPrice * 0.8; } } public class PriceContext { public Strategy Strategy { get; set; } public double GetPrice(double originalPrice) { return this.Strategy.CalcPrice(originalPrice); } }
調用端:blog
public class Test { public static void Entry() { Strategy strategy = new PrimaryStrategy(); PriceContext price = new PriceContext(); price.Strategy = strategy; Console.WriteLine(price.GetPrice(100)); //100 strategy = new IntermediateStrategy(); price.Strategy = strategy; Console.WriteLine(price.GetPrice(100)); //90 strategy = new AdvancedStrategy(); price.Strategy = strategy; Console.WriteLine(price.GetPrice(100)); //80 } }
示例中有若干具體的策略類,以及一個context對象,context對象會隨着策略對象的改變而變動其執行算法。接口
策略模式的優勢get
策略模式的缺點it
策略模式的適用場景電商