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

posted on 2013-12-06 14:49  backslash112  阅读(294)  评论(0编辑  收藏  举报

导航