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

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

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

```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 orderdecimal 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 orderdecimal orderTotal = products.Sum(p => p.Price);
orderTotal -= orderTotal * customer.DiscountPercentage;return orderTotal;
}
}
}```

+ 关注