您的位置:首页 > 编程语言

31天重构指南之三十一:使用多态代码条件判断

2009-11-06 16:53 323 查看
31天重构指南的最后一个重构来自于Fowlers的重构目录,你可以在这里查看。

这里展示了面向对象编程的基础之一“多态性”,有时你需要检查对象的类型,并根据类型进行一些操作,在这种情况下将算法封装到类中,并利用多态性进行抽象调用是一个好主意。

1:publicabstractclassCustomer
2:{
3:}
4:
5:publicclassEmployee:Customer
6:{
7:}
8:
9:publicclassNonEmployee:Customer
10:{
11:}
12:
13:publicclassOrderProcessor
14:{
15:publicdecimalProcessOrder(Customercustomer,IEnumerable<Product>products)
16:{
17://dosomeprocessingoforder
18:decimalorderTotal=products.Sum(p=>p.Price);
19:
20:TypecustomerType=customer.GetType();
21:if(customerType==typeof(Employee))
22:{
23:orderTotal-=orderTotal*0.15m;
24:}
25:elseif(customerType==typeof(NonEmployee))
26:{
27:orderTotal-=orderTotal*0.05m;
28:}
29:
30:returnorderTotal;
31:}
32:}
在上面的代码中,我们违反了SRP(SingleResponsibilityPrinciple)职责,要想对上面的代码进行得构,我们只需要将百分率移除到特定的customer子类中,
1:publicabstractclassCustomer
2:{
3:publicabstractdecimalDiscountPercentage{get;}
4:}
5:
6:publicclassEmployee:Customer
7:{
8:publicoverridedecimalDiscountPercentage
9:{
10:get{return0.15m;}
11:}
12:}
13:
14:publicclassNonEmployee:Customer
15:{
16:publicoverridedecimalDiscountPercentage
17:{
18:get{return0.05m;}
19:}
20:}
21:
22:publicclassOrderProcessor
23:{
24:publicdecimalProcessOrder(Customercustomer,IEnumerable<Product>products)
25:{
26://dosomeprocessingoforder
27:decimalorderTotal=products.Sum(p=>p.Price);
28:
29:orderTotal-=orderTotal*customer.DiscountPercentage;
30:
31:returnorderTotal;
32:}
33:}


原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/28/refactoring-day-31-replace-conditional-with-polymorphism.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: