重构第31天 使用多态替代条件语句( Replace conditional with Polymorphism)

理解:本文中的”使用多态代替条件判断”是指如果你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用。

详解:本文展示了面向对象编程的基础之一“多态性”, 有时你需要检查对象的类型或者根据类型执行一些操作时,一种很好的办法就是将算法封装到类中,并利用多态性进行抽象调用。

如下代码所示,OrderProcessor 类的ProcessOrder方法根据Customer 的类型分别执行一些操作,正如上面所讲的那样,我们最好将OrderProcessor 类中这些算法(数据或操作)封装在特定的Customer 子类中。

 

 1 public abstract class Customer
 2     {
 3     }
 4 
 5     public class Employee : Customer
 6     {
 7     }
 8 
 9     public class NonEmployee : Customer
10     {
11     }
12 
13     public class OrderProcessor
14     {
15         public decimal ProcessOrder(Customer customer, IEnumerable<Product> products)
16         {
17             // do some processing of order
18             decimal orderTotal = products.Sum(p => p.Price);
19 
20             Type customerType = customer.GetType();
21             if (customerType == typeof(Employee))
22             {
23                 orderTotal -= orderTotal * 0.15m;
24             }
25             else if (customerType == typeof(NonEmployee))
26             {
27                 orderTotal -= orderTotal * 0.05m;
28             }
29 
30             return orderTotal;
31         }
32     }

重构后的代码如下,每个Customer 子类都封装自己的算法,然后OrderProcessor 类的ProcessOrder方法的逻辑也变得简单并且清晰了。

 1 public abstract class Customer
 2     {
 3         public abstract decimal DiscountPercentage { get; }
 4     }
 5 
 6     public class Employee : Customer
 7     {
 8         public override decimal DiscountPercentage
 9         {
10             get { return 0.15m; }
11         }
12     }
13 
14     public class NonEmployee : Customer
15     {
16         public override decimal DiscountPercentage
17         {
18             get { return 0.05m; }
19         }
20     }
21 
22     public class OrderProcessor
23     {
24         public decimal ProcessOrder(Customer customer, IEnumerable<Product> products)
25         {
26             // do some processing of order
27             decimal orderTotal = products.Sum(p => p.Price);
28 
29             orderTotal -= orderTotal * customer.DiscountPercentage;
30 
31             return orderTotal;
32         }
33     }

 

 

原文地址:https://www.cnblogs.com/yplong/p/5381497.html