![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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; } } }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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