理解:本文中的“提取方法对象”是指当你发现一个方法中存在过多的局部变量时,你可以通过使用“提取方法对象”重构来引入一些方法,每个方法完成任务的一个步骤,这样可以使得程序变得更具有可读性。
详解:如下代码所示,Order 类中的Calculate方法要完成很多功能,在之前我们用“提取方法”来进行重构,现在我们采取“提取方法对象”来完成重构。
重构前代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ReflectorDemo
{
public class OrderLineItem
{
public decimal Price { get;private set; } } public class Order
{
private IList<OrderLineItem> OrderLineItems { get; set; } private IList<decimal> Discounts { get; set; } private decimal Tax { get; set; }
public decimal Calculate()
{
decimal subTotal = 0m; //Total up line items foreach (OrderLineItem lineItem in OrderLineItems)
{ subTotal += lineItem.Price;
} //substract Discounts
foreach (decimal discount in Discounts)
{
subTotal -= discount;
} //Calculate Tax decimal tax = subTotal*Tax; //calculate GrandTotal decimal grandtotal = subTotal + tax; return grandtotal;
}
}
}
提取方法对象重构后代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ReflectorDemo
{
public class OrderLineItem
{
public decimal Price { get; private set; } } public class Order
{
public IEnumerable<OrderLineItem> OrderLineItems { get; private set; } public IEnumerable<decimal> Discounts { get; private set; } public decimal Tax { get; private set; } public decimal Calculate()
{ return new OrderCaculator(this).Calculate();
} }
public class OrderCaculator
{
private decimal SubTotal { get; set; } private IEnumerable<OrderLineItem> OrderLineItems { get; set; } private IEnumerable<decimal> Discounts { get; set; } private decimal Tax { get; set; } public OrderCaculator(Order order)
{
OrderLineItems = order.OrderLineItems; Discounts = order.Discounts; Tax = order.Tax; } public decimal Calculate()
{ CalculateSubTotal(); SubstractDiscounts(); CalculateTax(); return SubTotal;
}
private void CalculateSubTotal()
{ foreach (OrderLineItem lineItem in OrderLineItems)
{
SubTotal += lineItem.Price;
}
} private void SubstractDiscounts()
{
foreach (decimal discount in Discounts)
{
SubTotal -= discount;
}
} private void CalculateTax()
{
SubTotal += SubTotal * Tax;
}
}
}
这种重构在我工作中用的还是比较少,很大程度上我们都会选择“提取方法”。