Replace conditional with Polymorphism
namespace RefactoringLib.Ploymorphism.Before { public class Customer { } public class Employee : Customer { } public class NonEmployee : Customer { } public class OrderProcessor { public decimal ProcessOrder(Customer customer, IEnumerable<Product> products) { decimal orderTotal = products.Sum(p => p.Price); Type customerType = customer.GetType(); if (customerType == typeof(Employee)) { orderTotal -= orderTotal * 0.15m; } else if (customerType == typeof(NonEmployee)) { orderTotal -= orderTotal * 0.05m; } return orderTotal; } } }
namespace RefactoringLib.Ploymorphism.End { public abstract class Customer { public abstract decimal DiscountPercentage { get; } } public class Employee : Customer { public override decimal DiscountPercentage { get { return 0.15m; } } } public class NonEmployee : Customer { public override decimal DiscountPercentage { get { return 0.05m; } } } public class OrderProcessor { public decimal ProcessOrder(Customer customer, IEnumerable<Product> products) { decimal orderTotal = products.Sum(p => p.Price); orderTotal -= orderTotal * customer.DiscountPercentage; return orderTotal; } } }
参考:Refactoring Day 31 : Replace Conditional with Polymorphism
作者: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 14:49 backslash112 阅读(294) 评论(0) 编辑 收藏 举报