您的位置:首页 > 其它

重构第四天 : 用多态替换条件语句(if else & switch)

2014-06-30 14:30 507 查看
面相对象的一个核心基础就是多态,当你要根据对象类型的不同要做不同的操作的时候,一个好的办法就是采用多态,把算法封装到子类当中去。

重构前代码

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


重构后的代码:

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐