在策略模式中,一个类的行为或算法能够在运行时动态更改。算法
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
策略模式的适用场景电商