31天重構學習筆記31. 使用多態代替條件判斷

摘要:由於最近在做重構的項目,所以對重構又重新進行了一遍學習和整理,對31天重構最早接觸是在2009年 10月份,由於當時沒有訂閱Sean Chambers的blog,所以是在國外的社區上閒逛的時候鏈接過去的。記得當時一口氣看完了整個系列並沒有多少感覺,因爲這些基本上項目都在使用,只是我們沒有專門把它標示和整理出來,所以也沒有引起多大的重視。現在突然接手這個重構項目,由於團隊成員技術和經驗參差不齊,所以有必要專門整理一個重構的綱要,當然這個系列也非常適合做新系統的代碼規範參考,只要有代碼的地方,這個重構規範就很有價值。週末也不想出去閒逛,因爲在剛到這個美麗的城市,沒有親戚或者朋友,所以才能靜下心來兩天時間寫完這個重構參考規範。同時也感受了Windows Live writer寫文章的快感。當然重構的整體架構得另當別論(整體架構在我的這篇文章有專門的講解(http://www.cnblogs.com/zenghongliang/archive/2010/06/23/1763438.html)。大的架構設計好了以後,這些重構細節點就成了東風之後的大火,對整個項目也是至關重要。31天重構這個系列和《代碼大全》、《重構:改善既有代碼的設計》比較起來最大的特點就是比較簡單、淺顯易懂。那麼我這些文章也都是學習Sean Chambers的31天重構的筆記整理,所以如果大家對這個筆記有任何異議也可以指出。

具體也可以通過http://www.lostechies.com/blogs/sean_chambers/archive/2009/07/31/31-days-of-refactoring.aspx查看原文。

 

概念:本文中的”使用多態代替條件判斷”是指如果你需要檢查對象的類型或者根據類型執行一些操作時,一種很好的辦法就是將算法封裝到類中,並利用多態性進行抽象調用。

 

正文:本文展示了面向對象編程的基礎之一“多態性”, 有時你需要檢查對象的類型或者根據類型執行一些操作時,一種很好的辦法就是將算法封裝到類中,並利用多態性進行抽象調用。

如下代碼所示,OrderProcessor 類的ProcessOrder方法根據Customer 的類型分別執行一些操作,正如上面所講的那樣,我們最好將OrderProcessor 類中這些算法(數據或操作)封裝在特定的Customer 子類中。

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;
}
}
}

 

重構後的代碼如下,每個Customer 子類都封裝自己的算法,然後OrderProcessor 類的ProcessOrder方法的邏輯也變得簡單並且清晰了。

 

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;
}
}
}

 

總結: ”使用多態代替條件判斷“這個重構在很多時候會出現設計模式中(常見的工廠家族、策略模式等都可以看到它的影子),因爲運用它可以省去很多的條件判斷,同時也能簡化代碼、規範類和對象之間的職責。

發佈了101 篇原創文章 · 獲贊 7 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章