1、搬移函数(Move Method)
(1)症状:如果一个类有太多行为,或一个类与另一个类有太多合作而形成高度耦和
(2)解决:在该函数最常引用的类中建立一个有着类似行为的新函数,将旧函数变成一个单纯的委托函数,或者是将旧函数完全移除
(3)检查:调用端、被调用端、继承体系中任何一个重定义函数
(4)如果源函数包含异常,需要判断逻辑上应该由哪个类来处理这一异常,如果应该由源类来负责,就把异常留在原地
(5)可以删除源函数,或将它当作一个委托函数保留下来
(6)如果要移除源函数,请将源类中对源函数的所有调用都替换成对目标函数的调用
//某银行系统中包含一个银行账户类BankAccount和账户利息类AccountInterest
class BankAccount {
private int accountAge;
private int creditScore;
private AccountInterest accountInterest;
public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest) {
this.accountAge = accountAge;
this.creditScore = creditScore;
this.accountInterest = accountInterest;
}
public int getAccountAge() {
return this.accountAge;
}
public int getCreditScore() {
return this.creditScore;
}
public AccountInterest getAccountInterest() {
return this.accountInterest;
}
public double calculateInterestRate() {
if (this.creditScore > 800) {
return 0.02;
}
if (this.accountAge > 10) {
return 0.03;
}
return 0.05;
}
}
class AccountInterest {
private BankAccount account;
public AccountInterest(BankAccount account) {
this.account = account;
}
public BankAccount getAccount() {
return this.account;
}
public double getInterestRate() {
return account.calculateInterestRate();
}
public boolean isIntroductoryRate() {
return (account.calculateInterestRate() < 0.05);
}
}
说明:很明显AccountInterest使用calculateInterestRate()方法更为频繁,它更希望得到该方法
----------------------------------------------------------------------------
重构(搬移函数)
将calculateInterestRate()方法从BankAccount类搬移到AccountInterest类中
class BankAccount {
private int