package cn.toltech.refactor.demo3;
/**
* Created by sz0816 on 15-1-7.
* 以函数对象取代函数
* 1、建立一个新类,根据待处理函数的用途,为这个类命名。
* 2、在新类中建立一个const字段,用以保存原来大型函数所在的对象。我们将这个字段称为“源对象”。
* 同时,针对原函数的每个临时变量和每个参数,在新类中建立一个对应的字段保存之。
* 3、在新类中建立一个构造函数,接收源对象及原函数的所有参数。
* 4、在新类中建立一个compute()函数。
* 5、将原函数的代码复制到compute()函数中。如果需要调用源对象的任何函数,请通过源对象字段调用。
*/
public class ReplaceMethodWithObject {
/***
* 在函数中有大量的临时变量,提取方法的时比较乱
*/
public int gamma(int inputVal,int quantity,int yearToDate){
int importantValue1 = (inputVal * quantity)+100;
int importantValue2 = (inputVal * yearToDate)+100;
if((yearToDate-importantValue1)>100){
importantValue2-=20;
}
int importantValue3 = importantValue2 * 7;
return importantValue3 - 2*importantValue1;
}
public int gammaRepair(int inputVal,int quantity,int yearToDate){
return new RepMethodObject(inputVal,quantity,yearToDate).gamma();
}
}
class RepMethodObject{
private int inputVal;
private int quantity;
private int yearToDate;
private int importantValue1;
private int importantValue2;
public RepMethodObject(int inputVal,int quantity,int yearToDate){
this.inputVal = inputVal;
this.quantity = quantity;
this.yearToDate = yearToDate;
}
public int gamma(){
importantValue1 = (inputVal * quantity)+100;
importantValue2 = (inputVal * yearToDate)+100;
if((yearToDate-importantValue1)>100){
importantValue2-=20;
}
int importantValue3 = importantValue2 * 7;
return importantValue3 - 2*importantValue1;
}
}
重构-以函数对象取代函数
最新推荐文章于 2023-03-16 20:29:18 发布