多態(polymorphism)是面向對象的重要特性,簡單可理解為:一個介面,多種實現。 當你的代碼中存在通過不同的類型執行不同的操作,包含大量if else或者switch語句時,就可以考慮進行重構,將方法封裝到類中,並通過多態進行調用。 代碼重構前: 代碼重構後: 重構後的代碼,將變化點封裝在了 ...
多態(polymorphism)是面向對象的重要特性,簡單可理解為:一個介面,多種實現。
當你的代碼中存在通過不同的類型執行不同的操作,包含大量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; } } }
重構後的代碼,將變化點封裝在了子類中,代碼的可讀性和可擴展性大大提高。