理解:本文中的”使用多态代替条件判断”是指如果你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用。
详解:本文展示了面向对象编程的基础之一“多态性”, 有时你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用。
如下代码所示,OrderProcessor 类的ProcessOrder方法根据Customer 的类型分别执行一些操作,正如上面所讲的那样,我们最好将OrderProcessor 类中这些算法(数据或操作)封装在特定的Customer 子类中。
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方法的逻辑也变得简单并且清晰了。
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;
}
}