一、定义
策略模式是针对一组算法,将每个算法封装到具有公共接口的独立的类中,从而使它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
二、UML类图
三、例子展示
namespace 策略者模式 { public interface ITaxStrategy { double GetTax(double money); } public class PersnalStrategy : ITaxStrategy { public double GetTax(double money) { return money * 0.1; } } public class EnterpriseTaxStrategy : ITaxStrategy { public double GetTax(double money) { return (money - 4000) > 0 ? (money - 4000) * 0.045 : 0.0; } } public class TaxContext { private ITaxStrategy _strategy; public TaxContext(ITaxStrategy taxStrategy) { _strategy = taxStrategy; } public double GetTax(double money) { return _strategy.GetTax(money); } } public class Client { public static void Process() { TaxContext taxContext = new TaxContext(new PersnalStrategy()); double tax = taxContext.GetTax(10000); Console.WriteLine("个人所得税:"+tax); taxContext = new TaxContext(new EnterpriseTaxStrategy()); tax = taxContext.GetTax(100000); Console.WriteLine("企业所得税:" + tax); // 与简单工厂模式一起,避免客户端既依赖于TaxContext,又依赖于具体策略者。这样客户端只需要知道TaxContext就可以了 TaxContext2 taxContext2 = new TaxContext2("PersnalStrategy"); double tax2 = taxContext2.GetTax(10000); Console.WriteLine("升级版 个人所得税:" + tax2); taxContext2 = new TaxContext2("EnterpriseTaxStrategy"); tax2 = taxContext2.GetTax(100000); Console.WriteLine("升级版 企业所得税:" + tax2); } } public class TaxContext2 { private ITaxStrategy _strategy; /// <summary> /// 简单工厂一起 /// </summary> /// <param name="taxType"></param> public TaxContext2(string taxType) { switch (taxType) { case "PersnalStrategy": _strategy = new PersnalStrategy(); break; case "EnterpriseTaxStrategy": _strategy = new EnterpriseTaxStrategy(); break; default: break; } } public double GetTax(double money) { return _strategy.GetTax(money); } } }