Replace Method with Method Object(以函数对象取代函数)
class order...
double price(){
double primaryBasePrice;
double secondaryBasePrice;
double tertiaryBasePrice;
// long computation
...
}
}
修改后:
做法
- 建立一个新类,根据待处理函数的用途,为这个类命名
- 在新类中建立一个final字段,用以保存原先大型函数所在的对象。我们将这个字段称为”源对象”。同时,针对原函数的每个临时变量和每个参数,在新类中建立一个对应的字段保存之
- 在新类中建立一个构造函数,接收源对象及原函数的所有参数作为参数
- 在新类中建立一个computer()函数
- 将原函数的代码复制到computer()函数中。如果需要调用源对象的任何函数,请通过源对象字段调用
- 编译
- 将旧函数的函数本体替换为这样一条语句:”创建上述新类的一个新对象,而后调用其中的computer()函数”
范例
class Account{
int gamma (int inputVal, int quantity, int yearToDate){
int importantValue1 = (inputVal * quantity) + delta();
int importantValue2 = (inputVal * yearToDate) + 100;
if ((yearToDate -importantValue1) > 100){
importantValue2 -= 20;
}
int importantValue3 = importantValue2 * 7;
// and so on.
return importantValue3 - 2 * importantValue1;
}
int delta() {
return 200;
}
}
创建新函数
class Gamma{
private final Account _account;
private int inputVal;
private int quantity;
private int yearToDate;
private int importantValue1;
private int importantValue2;
private int importantValue3;
Gamma(Account source, int inputValArg, int quantityArg, int yearToDateArg){
_account = source;
inputValArg = inputVal;
quantityArg = quantity;
yearToDateArg = yearToDate;
}
int compute(){
int importantValue1 = (inputVal * quantity) + _account.delta();
int importantValue2 = (inputVal * yearToDate) + 100;
if ((yearToDate -importantValue1) > 100){
importantValue2 -= 20;
}
int importantValue3 = importantValue2 * 7;
// and so on.
return importantValue3 - 2 * importantValue1;
}
}
修改旧函数
int gamma (int inputVal, int quantity, int yearToDate){
return new Gamma(this,inputVal,quantity,yearToDate).compute();
}