重构指南 - 使用多态代替条件判断(Replace conditional with Polymorphism)

多态(polymorphism)是面向对象的重要特性,简单可理解为:一个接口,多种实现。

当你的代码中存在通过不同的类型执行不同的操作,包含大量if else或者switch语句时,就可以考虑进行重构,将方法封装到类中,并通过多态进行调用。

 

代码重构前:

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;
        }
    }
}

 

代码重构后:

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;
        }
    }
}

 

重构后的代码,将变化点封装在了子类中,代码的可读性和可扩展性大大提高。

 

转载于:https://www.cnblogs.com/hmloo/p/6872337.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值