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.
顺序 选择 循环 总结
相关文章
- javascript语言扩展:可迭代对象(1)
- JavaScript中的Function(函数)对象详解
- 设计模式 ( 十三 ) 命令模式Command(对象行为型)
- 函数对象http://blog.csdn.net/bonchoix/article/details/8050627
- js Date对象的扩展函数
- JavaScript 浏览器对象模型 (BOM)
- 内建函数对象---算术仿函数
- Atitit 持久化 之道 attilax 艾龙著 1. 第2章 Java对象持久化技术概述 2 1.1. 2.1 直接通过JDBC API来持久化实体域对象2 1.2. 2.2 ORM简介2
- paip.提升性能----java 无锁结构(CAS, Atomic, Threadlocal, volatile, 函数式编码, 不变对象)
- java list按照元素对象的指定多个字段属性进行排序
- Python编程语言学习:python语言中快速查询python自带模块&函数的用法及其属性方法、如何查询某个函数&关键词的用法、输出一个类或者实例化对象的所有属性和方法名之详细攻略
- 【JVM与内存调优】Java中五种创建对象的方式 与 HotSpot虚拟机对象探秘
- 9个GaussDB常用的对象语句
- 习题 9.11 将例9.13中的Time类声明为Date类的友元类,通过Time类中的display函数引用Date类对象的私有数据,输出年、月、日和时、分、秒。
- QTextEdit添加文本对象(将N个文字结合成一个整体)
- java使用BeanUtils封装file类型表单数据到一个对象中
- 统计输入的单词中有几个长度大于n的,n是自己指定的,用函数对象实现
- javascript中构造函数的返回值问题和new对象的过程
- 使用GDIView工具排查GDI对象泄漏问题(常用分析工具)
- 用句柄操纵对象
- Pandas高阶--第一节 层级索引、分组与聚合介绍、GroupBy对象及常用的聚合操作、自定义分组及聚合操作
- 函数对象--仿函数
- 详解javaScript的事件中,复杂数据类型的传参(数组,对象,函数)
- 黑马C++笔记——函数对象(仿函数)
- __getattribute__的妙用,实现对象实例的“继承“与方法重载
- 【跟学C++】C++类与对象—构造函数—析构函数(Study10)
- 第十篇:反射,从字节码到对象