經過策略模式來重構優化代碼裏面的switch/case分支代碼。極大程度上提升了程序的擴展性。固然,若是分支比較多,每次都須要新增長一個類,這的確是有點麻煩,能夠考慮使用反射來實現。
代碼:html
namespace DP { public enum State { Alaska, NewYork, Florida } public class CalculateShippingAmount { public CalculateShippingAmount(IDictionary<State, IGetShippingAmount> dic) => _dic = dic; private IDictionary<State, IGetShippingAmount> _dic { get; set; } public decimal Calculate(State state) => _dic[state].GetAmount(); } public interface IGetShippingAmount { decimal GetAmount(); } #region 具體地址的實現 // 具體 public class GetAlaskaShippingAmount : IGetShippingAmount { public decimal GetAmount() => 15; } public class GetNewYorkShippingAmount : IGetShippingAmount { public decimal GetAmount() => 10; } public class GetFloridaShippingAmount : IGetShippingAmount { public decimal GetAmount() => 3; } #endregion }
調用:優化
#region 策略模式重構 switch...case... static void SwitchToStrategy() { var dic = new Dictionary<State, IGetShippingAmount> { {State.Alaska, new GetAlaskaShippingAmount() }, {State.Florida, new GetFloridaShippingAmount() }, {State.NewYork, new GetNewYorkShippingAmount() } }; var calculate = new CalculateShippingAmount(dic); var result = calculate.Calculate(State.Florida); Console.WriteLine($"{State.Florida.ToString()}返回{result}"); } #endregion
參考:使用策略模式重構switch case 代碼spa