Replace Method with Method Object(以函数对象取代函数)

  1. class order...
  2. double price(){
  3. double primaryBasePrice;
  4. double secondaryBasePrice;
  5. double tertiaryBasePrice;
  6. // long computation
  7. ...
  8. }
  9. }

修改后:

8.Replace Method with Method Object(以函数对象取代函数) - 图1

做法

  • 建立一个新类,根据待处理函数的用途,为这个类命名
  • 在新类中建立一个final字段,用以保存原先大型函数所在的对象。我们将这个字段称为”源对象”。同时,针对原函数的每个临时变量和每个参数,在新类中建立一个对应的字段保存之
  • 在新类中建立一个构造函数,接收源对象及原函数的所有参数作为参数
  • 在新类中建立一个computer()函数
  • 将原函数的代码复制到computer()函数中。如果需要调用源对象的任何函数,请通过源对象字段调用
  • 编译
  • 将旧函数的函数本体替换为这样一条语句:”创建上述新类的一个新对象,而后调用其中的computer()函数”

范例

  1. class Account{
  2. int gamma (int inputVal, int quantity, int yearToDate){
  3. int importantValue1 = (inputVal * quantity) + delta();
  4. int importantValue2 = (inputVal * yearToDate) + 100;
  5. if ((yearToDate -importantValue1) > 100){
  6. importantValue2 -= 20;
  7. }
  8. int importantValue3 = importantValue2 * 7;
  9. // and so on.
  10. return importantValue3 - 2 * importantValue1;
  11. }
  12. int delta() {
  13. return 200;
  14. }
  15. }

创建新函数

  1. class Gamma{
  2. private final Account _account;
  3. private int inputVal;
  4. private int quantity;
  5. private int yearToDate;
  6. private int importantValue1;
  7. private int importantValue2;
  8. private int importantValue3;
  9. Gamma(Account source, int inputValArg, int quantityArg, int yearToDateArg){
  10. _account = source;
  11. inputValArg = inputVal;
  12. quantityArg = quantity;
  13. yearToDateArg = yearToDate;
  14. }
  15. int compute(){
  16. int importantValue1 = (inputVal * quantity) + _account.delta();
  17. int importantValue2 = (inputVal * yearToDate) + 100;
  18. if ((yearToDate -importantValue1) > 100){
  19. importantValue2 -= 20;
  20. }
  21. int importantValue3 = importantValue2 * 7;
  22. // and so on.
  23. return importantValue3 - 2 * importantValue1;
  24. }
  25. }

修改旧函数

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