6.8replace method with method object(以函数对象取代函数)


动机:

 将这个函数放进一个单独对象中,如此一来局部变量就成了对象内的字段。然后你可以在同一个对象中将这个大型函数分解为多个小型函数。

做法:

建立一个新类,根据待处理函数的用途,为这个类命名。

在新类中建立一个final字段,用以保存原先大型函数所在的对象。我们将这个字段称为“源对象”。同时,针对原函数的每个临时变量和每个参数,在新类中建立一个对应的字段保存之。

在新类中建立一个构造函数,接受源对象及原函数的所有参数作为参数。

在新类中建立一个compute()函数。

将原函数的代码复制到compute()函数中。如果需要调用源对象的任何函数,请通过源对象字段调用。

将旧函数的函数本体替换为这样一条语句:“创建上述新类的一个新对象,而后调用其中的compute()函数”。

范例:

旧代码

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;
    return importantValue3 - 2 * importantValue1;
}

 

新代码

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;
    inputVal = inputValArg;
    quantity = quantityArg;
    yearToDate = yearToDateArg;
}
int compute(){
    importantValue1 = (inputVal * quantity) + _account.delta();
    importantValue2 = (inputVal * yearToDate) + 100;
    importantthing();
    int importantValue3 = importantValue2 * 7;
    return importantValue3 - 2 * importantValue1;
}
void importantThing(){
    if((yearToDate - importantValue1) > 100)
        importantValue2 -= 20;
}

int gamma(int inputVal, int quantity, int yearToDate){
    return new Gamma(this, inputVal, quantity, yearToDate).compute();
}

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值