【设计模式】 策略模式
一. 策略模式
1. 对相同功能不同实现的一系列算法的封装, 使切换算法时不会影响调用者
2. 适用场景 :
a. 需要根据条件频繁切换算法的地方
3. 代码
class Strategy { public static void Test() { double money = 600; DiscountBase discount = DiscountFactory.GetDiscount("打折"); if (discount!=null) { double result = discount.GetResult(money); } } } internal class DiscountFactory { public static DiscountBase GetDiscount(string type) { switch (type) { case "原价": return new NoDiscount(); case "打折": return new OffDiscount(); case "满500减300": return new MulDiscount(); default: return null; } } } internal abstract class DiscountBase { public abstract double GetResult(double a); } internal class NoDiscount : DiscountBase { public override double GetResult(double a) { return a; } } internal class OffDiscount : DiscountBase { public override double GetResult(double a) { return a * 0.8; } } internal class MulDiscount : DiscountBase { public override double GetResult(double a) { if (a > 500) { return a - 300; } return a; } }