Switch to strategy
namespace RefactoringLib.SwitchToStrategy.Before { public class ClientCode { public decimal CalculateShipping() { ShippingInfo shippingInfo = new ShippingInfo(); return shippingInfo.CalculateShippingAmount(State.Alaska); } } public enum State { Alaska, NewYork, Florida } public class ShippingInfo { public decimal CalculateShippingAmount(State shipToState) { switch (shipToState) { case State.Alaska: return GetAlaskaShippingAmount(); case State.NewYork: return GetNewYorkShippingAmount(); case State.Florida: return GetFloridaShippingAmount(); default: return 0m; } } private decimal GetAlaskaShippingAmount() { return 15m; } private decimal GetNewYorkShippingAmount() { return 10m; } private decimal GetFloridaShippingAmount() { return 3m; } } }
namespace RefactoringLib.SwitchToStrategy.End { public class ClientCode { public decimal CalculateShipping() { ShippingInfo shippingInfo = new ShippingInfo(); return shippingInfo.CalculateShippingAmount(State.Alaska); } } public enum State { Alaska, NewYork, Florida } public class ShippingInfo { public IDictionary<State, IShippingCalculaton> ShippingCalculatons { get; set; } public ShippingInfo() { ShippingCalculatons = new Dictionary<State, IShippingCalculaton> { { State.Alaska, new AlaskaShippingCalculation() }, { State.NewYork, new NewYorkShippingCalculation() }, { State.Florida, new FloridaShippingCalculation() } }; } public decimal CalculateShippingAmount(State state) { return ShippingCalculatons[state].Calculate(); } } public interface IShippingCalculaton { decimal Calculate(); } public class AlaskaShippingCalculation : IShippingCalculaton { public decimal Calculate() { return 15m; } } public class NewYorkShippingCalculation : IShippingCalculaton { public decimal Calculate() { return 10m; } } public class FloridaShippingCalculation : IShippingCalculaton { public decimal Calculate() { return 5m; } } }
参考:Refactoring Day 11 : Switch to Strategy
作者:backslash112 (美国CS研究生在读/机器人工程师)
出处:http://sirkevin.cnblogs.com
GitHub:https://github.com/backslash112
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://sirkevin.cnblogs.com
GitHub:https://github.com/backslash112
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
posted on 2013-12-06 10:56 backslash112 阅读(202) 评论(0) 编辑 收藏 举报