重构指南 - 使用多态代替条件判断(Replace conditional with Polymorphism)
2017-05-18 11:09
537 查看
多态(polymorphism)是面向对象的重要特性,简单可理解为:一个接口,多种实现。
当你的代码中存在通过不同的类型执行不同的操作,包含大量if else或者switch语句时,就可以考虑进行重构,将方法封装到类中,并通过多态进行调用。
代码重构前:
代码重构后:
重构后的代码,将变化点封装在了子类中,代码的可读性和可扩展性大大提高。
当你的代码中存在通过不同的类型执行不同的操作,包含大量if else或者switch语句时,就可以考虑进行重构,将方法封装到类中,并通过多态进行调用。
代码重构前:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LosTechies.DaysOfRefactoring.SampleCode.BreakMethod.After; namespace LosTechies.DaysOfRefactoring.SampleCode.ReplaceWithPolymorphism.Before { public abstract class Customer { } public class Employee : Customer { } public class NonEmployee : Customer { } public class OrderProcessor { public decimal ProcessOrder(Customer customer, IEnumerable<Product> products) { // do some processing of order 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; } } }
代码重构后:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LosTechies.DaysOfRefactoring.SampleCode.BreakMethod.After; namespace LosTechies.DaysOfRefactoring.SampleCode.ReplaceWithPolymorphism.After { 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) { // do some processing of order decimal orderTotal = products.Sum(p => p.Price); orderTotal -= orderTotal * customer.DiscountPercentage; return orderTotal; } } }
重构后的代码,将变化点封装在了子类中,代码的可读性和可扩展性大大提高。
相关文章推荐
- 重构31-Replace conditional with Polymorphism(多态代替条件)
- 重构第31天 使用多态替代条件语句( Replace conditional with Polymorphism)
- 重构手法39:Replace Conditional with Polymorphism (以多态取代条件表达式)
- 31天重构学习笔记31. 使用多态代替条件判断
- 31天重构学习笔记31. 使用多态代替条件判断
- 简化条件表达式之六 :Replace Conditional with Polymorphism(以多态取代条件式)
- 31天重构学习笔记31. 使用多态代替条件判断
- 31天重构学习笔记31. 使用多态代替条件判断
- Replace Conditional with Polymorphism (以多态取代条件表达式)
- 31 天重构学习笔记31. 使用多态代替条件判断
- 31天重构学习笔记31. 使用多态代替条件判断
- 9.6 replace conditional with polymorphism (以多态取代条件表达式)
- 31天重构指南之十八:使用条件判断代替异常
- 重构第18天 用条件语句来代替异常(Replace exception with conditional)
- 31天重构指南之三十一:使用多态代码条件判断
- 重构手法38:Replace Nested Conditional with Guard Clauses (以卫语句取代嵌套条件表达式)
- 重构18-Replace exception with conditional(条件替代异常)
- 重构第8天:使用委托代替继承(Replace Inheritance with Delegation)
- 使用多态代替条件判断
- 31天重构学习笔记18. 使用条件判断代替异常