2.2 搬移字段

【1】源代码

 1 // 重构前
 2 class Account
 3 {
 4 public:
 5     double interestForAmount_days(double amount, int days)
 6     {
 7         return m_dInterestRate * amount * days / 365;
 8     }
 9 
10 private:
11     AccountType m_type;
12     double m_dInterestRate; // 利率随类型变化,所以准备搬移该字段
13 };

【2】搬移字段

// 重构后
class Account
{
public:
    double interestForAmount_days(double amount, int days)
    {
        return m_type.getInterestRate() * amount * days / 365;
    }

private:
    AccountType m_type;
};

class AccountType
{
public:
    double getInterestRate()
    {
        return m_dInterestRate;
    }
    void setInterestRete(double dValue)
    {
        m_dInterestRate = dValue;
    }

private:
    double m_dInterestRate; // 利率随类型变化,所以准备搬移该字段
};

【3】总结

程序中,某个字段被其所驻类之外的另一个类更多的用到。在目标类新建一个字段,修改源字段的所有用户,令他们改用新字段。

如果发现,对于一个字段,在其所驻类之外的另一个类中有更多函数使用了它,我就会考虑搬移这个字段。

Good Good Study, Day Day Up.

顺序 选择 循环 总结

原文地址:https://www.cnblogs.com/Braveliu/p/7341091.html