代码改变世界

31天重构学习笔记31. 使用多态代替条件判断

2010-06-29 17:31  圣殿骑士  阅读(5393)  评论(18编辑  收藏  举报

摘要:由于最近在做重构的项目,所以对重构又重新进行了一遍学习和整理,对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;
}
}
}

 

总结: ”使用多态代替条件判断“这个重构在很多时候会出现设计模式中(常见的工厂家族、策略模式等都可以看到它的影子),因为运用它可以省去很多的条件判断,同时也能简化代码、规范类和对象之间的职责。