重构来自于Martin Fowler的重构目录。你可以在这里找到包含简介的原始文章。
在我看来,这是一个比较罕见的重构,但有时却终能派上用场。当你尝试进行提取方法的重构时,需要引入大量的方法。在一个方法中使用众多的本地变量有时会使代码变得丑陋。因此最好使用提取方法对象这个重构,将执行任务的逻辑分开
public class OrderLineItem {
public Double Price;
}
public class Order {
private List<OrderLineItem> OrderLineItems;
private List<Double> Discounts;
private Double Tax;
public Double Calculate() {
Double subTotal = 0d;
// Total up line items
for(OrderLineItem lineItem : OrderLineItems) {
subTotal += lineItem.Price;
}
// Subtract Discounts
for(Double discount : Discounts) subTotal -= discount;
// Calculate Tax
Double tax = subTotal * Tax;
// Calculate GrandTotal
Double grandTotal = subTotal + tax;
return grandTotal;
}
}
我们通过构造函数,将返回计算结果的类的引用传递给包含多个计算方法的新建对象,或者向方法对象的构造函数中单独传递各个参数。如下面的代码:
public class OrderLineItem{
public Double Price;
}
public class Order {
public List<OrderLineItem> OrderLineItems;
public List<Double> Discounts;
public Double Tax;
public Double Calculate() {
return new OrderCalculator(this).Calculate();
}
}
public class OrderCalculator {
private Double SubTotal;
private List<OrderLineItem> OrderLineItems;
private List<Double> Discounts;
private Double Tax;
public OrderCalculator(Order order) {
OrderLineItems = order.OrderLineItems;
Discounts = order.Discounts;
Tax = order.Tax;
}
public Double Calculate() {
CalculateSubTotal();
SubtractDiscounts();
CalculateTax();
return SubTotal;
}
private void CalculateSubTotal() {
// Total up line items
for(OrderLineItem lineItem : OrderLineItems) SubTotal += lineItem.Price;
}
private void SubtractDiscounts() {
// Subtract Discounts
for(Double discount : Discounts) SubTotal -= discount;
}
private void CalculateTax() {
// Calculate Tax
SubTotal += SubTotal * Tax;
}
}