Spiga

一天一个重构方法(39):以多态取代条件式

2009-10-17 17:06:14

Replace conditional with Polymorphism:以多态取代条件式

多态(Polymorphism)是面向对象编程的基本概念之一。在这里,是指在进行类型检查和执行某些类型操作时,最好将算法封装在类中,并且使用多态来对代码中的调用进行抽象

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

如你所见,我们没有利用已有的继承层次进行计算,而是使用了违反SRP 原则的执行方式。要进行重构,我们只需将百分率的计算置于实际的customer类型之中。我知道这只是一项补救措施,但我还是会这么做,就像在代码中那样。

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