博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1.7 以函数对象取代函数
阅读量:7033 次
发布时间:2019-06-28

本文共 2087 字,大约阅读时间需要 6 分钟。

【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 Gamma23 {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】总结

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

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

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

 

Good Good Study, Day Day Up.

顺序 选择 循环 总结

转载地址:http://hcyal.baihongyu.com/

你可能感兴趣的文章
树(7)-----二叉树的序列化和反序列化
查看>>
13.Fibonacci数
查看>>
easyui tab 关闭 打开
查看>>
ZendStudio快捷键
查看>>
前端性能优化
查看>>
浅谈 串行信号 转换成 并行信号 原理
查看>>
分布式系统(Distributed System)资料
查看>>
underscore.js库的浅析
查看>>
Android 通过软引用实现图片缓存,防止内存溢出
查看>>
EXT.NET常用控件使用
查看>>
C语言两种方式实现矩阵的转置
查看>>
javaee自定义servlet的步骤
查看>>
更进ATM
查看>>
C#和.Net的关系
查看>>
(转载)OpenStreetMap初探(一)——了解OpenStreetMap
查看>>
stm32F10x复习-1
查看>>
嵌入式技术学习路线
查看>>
目前为止最好的关于const的解释
查看>>
20145213《信息安全系统设计》第九周学习总结下篇
查看>>
thinkphp疑难解决4
查看>>