zoukankan      html  css  js  c++  java
  • Replace conditional with Polymorphism

    namespace RefactoringLib.Ploymorphism.Before
    {
        public class Customer { }
        
        public class Employee : Customer { }
        
        public class NonEmployee : Customer { }
        
        public class OrderProcessor
        {
            public decimal ProcessOrder(Customer customer, IEnumerable<Product> products)
            {
                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;
            }
        }
    }
    View Code

     

    namespace RefactoringLib.Ploymorphism.End
    {
        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)
            {
                decimal orderTotal = products.Sum(p => p.Price);
    
                orderTotal -= orderTotal * customer.DiscountPercentage;
    
                return orderTotal;
            }
        }
    
    }
    View Code

    参考:Refactoring Day 31 : Replace Conditional with Polymorphism

  • 相关阅读:
    关于区间数颜色的主席树解决
    1020考试总结
    QR算法
    新的征程
    端点星2020.12.2联赛
    自我介绍&友链
    3个搜索
    搜索格式这样写
    T107073 归并排序
    还有这个题
  • 原文地址:https://www.cnblogs.com/sirkevin/p/3461400.html
Copyright © 2011-2022 走看看