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

概念:本文中的”使用多态代替条件判断”是指如果你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用。

正文:本文展示了面向对象编程的基础之一“多态性”, 有时你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用。

如下代码所示,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;
}
}
}

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

 
原文地址:https://www.cnblogs.com/ywsoftware/p/2892639.html