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


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

重构前代码

 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 }

重构后的代码:

 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   }

优质内容筛选与推荐>>
1、数据库连接池-C3P0使用1
2、(3)HTML5 文件操作API
3、poj1936 假期计划第一水
4、JVM调优总结 -Xms -Xmx -Xmn -Xss
5、【转】Android类动态加载技术


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn