## 31天重构学习笔记31. 使用多态代替条件判断

2010-06-29 17:31  圣殿骑士  阅读(5244)  评论(18编辑  收藏  举报

using System;using System.Collections.Generic;using System.Linq;using System.Text;using LosTechies.DaysOfRefactoring.SampleCode.BreakMethod.After;namespace LosTechies.DaysOfRefactoring.SampleCode.ReplaceWithPolymorphism.Before{    public abstract class Customer    {    }    public class Employee : Customer    {    }    public class NonEmployee : Customer    {    }    public class OrderProcessor    {        public decimal ProcessOrder(Customer customer, IEnumerable<Product> products)        {            // do some processing of order            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;        }    }}

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

using System;using System.Collections.Generic;using System.Linq;using System.Text;using LosTechies.DaysOfRefactoring.SampleCode.BreakMethod.After;namespace LosTechies.DaysOfRefactoring.SampleCode.ReplaceWithPolymorphism.After{    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)        {            // do some processing of order            decimal orderTotal = products.Sum(p => p.Price);            orderTotal -= orderTotal * customer.DiscountPercentage;            return orderTotal;        }    }}