“Replace Method with Method Object”(以函数对象取代函数)。其做法是将函数放进一个单独的对象当中,使用这个单独对象的值域(filed)来替代原函数中的局部变量。这样做的好处是对于一个拥有较多较复杂的局部变量的函数来说的。

 

 
  
  1. package neusoft;  
  2.  
  3. /**  
  4.  * <p>Date       : 2012-03-15</p>  
  5.  * <p>Description: 以函数对象取代函数,解决局部变量过多问题</p>  
  6.  * @author 小俊垃圾回收站  
  7.  *   
  8.  */ 
  9. public class ReplaceMethodWithMethodObject {  
  10.     /*原来未重构代码  
  11.      int gamma(int inputVal, int quantity, int yearToDate) {  
  12.         int importantValue1 = (inputVal * quantity) + delta();  
  13.         int importantValue2 = (inputVal * yearToDate) + 100;  
  14.         if ((yearToDate - importantValue1) > 100) {  
  15.             importantValue2 -= 20;  
  16.         }  
  17.         int importantValue3 = importantValue2 * 7;  
  18.           
  19.         return importantValue3 - 2 * importantValue1;  
  20.     }*/ 
  21.       
  22.     /**  
  23.      * 重构后  
  24.      */ 
  25.     int gamma(int inputVal, int quantity, int yearToDate) {  
  26.  
  27.         // 将工作委托给函数对象  
  28.         return new Gamma(inputVal, quantity, yearToDate).gamma();  
  29.     }  
  30.  
  31.     private int delta() {  
  32.         return 5;  
  33.     }  
  34.  
  35.     /*  
  36.      * replace method with inner class method object(could be better than outer  
  37.      * class!)  
  38.      */ 
  39.       
  40.     class Gamma {  
  41.         private int inputVal;  
  42.         private int quantity;  
  43.         private int yearToDate;  
  44.         private int importantValue1;  
  45.         private int importantValue2;  
  46.         private int importantValue3;  
  47.           
  48.           
  49.         public Gamma(int inputVal, int quantity, int yearToDate) {  
  50.             this.inputVal = inputVal;  
  51.             this.quantity = quantity;  
  52.             this.yearToDate = yearToDate;  
  53.         }  
  54.  
  55.         int gamma() {  
  56.             importantValue1 = (inputVal * quantity) + delta();  
  57.             importantValue2 = (inputVal * yearToDate) + 100;  
  58.             importantValue2 = importantThing();  
  59.             importantValue3 = importantValue2 * 7;  
  60.  
  61.             return importantValue3 - 2 * importantValue1;  
  62.         }  
  63.  
  64.         private int importantThing() {  
  65.             if ((yearToDate - importantValue1) > 100) {  
  66.                 importantValue2 -= 20;  
  67.             }  
  68.             return importantValue2;  
  69.         }  
  70.     }  
  71.  
  72.     /**  
  73.      * test  
  74.      *   
  75.      * @param args  
  76.      */ 
  77.     public static void main(String[] args) {  
  78.  
  79.         System.out.print(new ReplaceMethodWithMethodObject().gamma(111));  
  80.     }  
  81. }  

 

本文参照《重构改善代码的设计》 

——————————————————————————————————————————小俊垃圾回收站