zoukankan      html  css  js  c++  java
  • 重构第四天 : 用多态替换条件语句(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   }
  • 相关阅读:
    AndroidWear开发之下载SDK[Android W/Android L]
    Androidの共享登录之方案研究
    AndroidのUI体验之ImmersiveMode沉浸模式
    谷歌Volley网络框架讲解——HttpStack及其实现类
    谷歌Volley网络框架讲解——网络枢纽
    05-使用jQuery操作input的values
    02-jQuery的选择器
    01-jQuery的介绍
    07-BOM client offset scroll 的系列
    06-js中的中的面向对象 定时器
  • 原文地址:https://www.cnblogs.com/peteryan/p/3816541.html
Copyright © 2011-2022 走看看