重构----使用多态代替条件判断

来源:互联网 发布:西南大学网络教育 编辑:程序博客网 时间:2024/06/05 22:32

public abstract class Customer
{
}

public class Employee: Customer
{
}

public class NonEmployee: Customer
{
}

public class OrderProcessor
{
public decimal ProcessOrder(Customercustomer, 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;
}
}
重构为:

 

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(Customercustomer, IEnumerable<Product> products)
{
// do some processing of order
decimal orderTotal = products.Sum(p => p.Price);

orderTotal -= orderTotal * customer.DiscountPercentage;

return orderTotal;
}
}

原创粉丝点击