以函数对象取代函数
重构导图
代码
/**
* 重构前
*/
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 Account {
int gamma(int inputVal, int quantity, int yearToDate) {
return new gamma(this, inputVal, quantity, yearToDate);
}
}
class Gamma {
private final Account account;
private int inputVal;
private int quantity;
private int yearToDate;
private int importantValue1;
private int importantValue2;
private int importantValue3;
public Gamma(Account account, int inputVal, int quantity, int yearToDate) {
this.account = account;
this.inputVal = inputVal;
this.quantity = quantity;
this.yearToDate = yearToDate;
}
public int compute() {
importantValue1 = (inputVal + quantity) + account.delta();
importantValue2 = (inputval * yearToDate) + 100;
if((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
importantValue3 = importantValue2 * 7;
return importantValue3 - 2 * importantValue1;
}
}
/**
* 提炼函数后
*/
class Account {
int gamma(int inputVal, int quantity, int yearToDate) {
return new gamma(this, inputVal, quantity, yearToDate);
}
}
class Gamma {
private final Account account;
private int inputVal;
private int quantity;
private int yearToDate;
private int importantValue1;
private int importantValue2;
private int importantValue3;
public Gamma(Account account, int inputVal, int quantity, int yearToDate) {
this.account = account;
this.inputVal = inputVal;
this.quantity = quantity;
this.yearToDate = yearToDate;
}
public int compute() {
importantValue1 = (inputVal + quantity) + account.delta();
importantValue2 = (inputval * yearToDate) + 100;
importantThing();
importantValue3 = importantValue2 * 7;
return importantValue3 - 2 * importantValue1;
}
private void importantThing() {
if((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
}
}
最后,欢迎大家加入设计模式重构技术交流QQ群,群号:809570546
点击链接加入群聊【设计模式-重构技术】:https://jq.qq.com/?_wv=1027&k=5nfECS7