zl程序教程

您现在的位置是:首页 >  后端

当前栏目

1.7 以函数对象取代函数

对象 函数 1.7 取代
2023-09-14 09:12:19 时间

【1】源代码

 1 // 重构前
 2 class Account
 3 {
 4 public:
 5     // 以下函数没有实际意义,为了演示使用过多的局部变量
 6     int gamma(int inputVal, int quantity, int yearTodate);
 7     {
 8         int importantValue1 = (inputVal * quantity) + delta();
 9         int importantValue2 = (inputVal * yearToDate) + 100;
10         if ((yearToDate - importantValue1) > 100)
11             importantValue2 -= 20;
12 
13         int importantValue3 = importantValue2 * 7;
14         // do something....
15         return importantValue3 - 2 * importantValue1;
16     }
17 
18     int delta() const { return 100; }
19 };

【2】以函数对象取代函数

 1 // 以函数对象取代函数
 2 class Account
 3 {
 4 public:
 5     int gamma(int inputVal, int quantity, int yearTodate);
 6     int delta() const
 7     {
 8         return 100;
 9     }
10 };
11 
12 // 修改Account类中的旧函数
13 int Account::gamma(int inputVal, int quantity, int yearToDate)
14 {
15     Gamma gm(this, inputVal, quantity, yearToDate);
16     return gm.compute();
17 }
18 
19 // 1.声明一个新类,提供一个const字段用以保存源对象
20 // 2.原函数的每一个参数和每一个临时变量分别以一个字段保存
21 // 3.加一个构造函数
22 class Gamma
23 {
24 public:
25     Gamma(Account* src, int inputVal, int quantity, int yearToDate)
26         : m_pAccount(src)
27         , m_nInputVal(inputVal)
28         , m_nQuantity(quantity)
29         , m_nYearToDate(yearToDate)
30     {}
31 
32     int compute()
33     {
34         m_nImportantValue1 = (m_nInputVal * m_nQuantity) + m_pAccount->delta(); // 调用源对象的delta()
35         m_nImportantValue2 = (m_nInputVal * m_nYearToDate) + 100;
36         if ((m_nYearToDate - m_nImportantValue1) > 100)
37         {
38             m_nImportantValue2 -= 20;
39         }
40 
41         m_nImportantValue3 = m_nImportantValue2 * 7;
42         // do something....
43         return m_nImportantValue3 - 2 * m_nImportantValue1;
44     }
45 
46 private:
47     const Account* m_pAccount;
48 
49     int m_nInputVal;
50     int m_nQuantity;
51     int m_nYearToDate;
52     int m_nImportantValue1;
53     int m_nImportantValue2;
54     int m_nImportantValue3;
55 };

【3】总结

有一个大型函数,其中对局部变量的使用使你无法采用[1.1提炼函数]。

将这个函数放进一个单独对象中,如此一来局部变量就成了对象内的字段。

然后,你可以在同一个对象中将这个大型函数分解为多个小型函数。

 

Good Good Study, Day Day Up.

顺序 选择 循环 总结