版权声明:请注明转发出处 https://blog.csdn.net/mafucun1988/article/details/89371933
《重构:改善既有代码的设计》中提到过很多重构方法,关于重新组织函数的方法有9种。本文介绍:
以函数对象取代函数 replace method with method object
- 名称:以函数对象取代函数 replace method with method object
- 概要:有一个大型函数,其中对局部变量的使用,使你无法采用extract method。将这个函数放进一个单独对象中,局部变量就变成了对象内的字段,然后将这个大型函数分解为多个小型函数。
- 动机:有一个大型函数,其中对局部变量的使用,使你无法采用extract method。
- 做法:
- 新建一个类,根据待处理函数的用途,为类命名
- 针对源函数的每个临时变量和每个参数,在新类中建立一个对应的字段保存
- 在新类中建立一个构造函数,接收源对象及原函数的所有参数作为参数
- 在新类中建立一个compute() 函数
- 将源函数的代码赋值到compute()函数中,如果需要调用源对象的任何函数,请通过源对象字段调用。
- 编译
- 将旧函数的函数本体替换为这样一条语句:“创建上述新类的一个新对象,而后调用其中的compute()函数”
- 代码演示:
修改之前的代码:
///////////////////////.h
#ifndef REFACTORMETHOD_H
#define REFACTORMETHOD_H
#include <QString>
#include <QVector>
class RefactorMethod
{
public:
int Gamma(int InputVal, int Quantity, int YearToDate);
int Delta();
};
#endif // REFACTORMETHOD_H
///////////////////////.cpp
int RefactorMethod::Gamma(int InputVal, int Quantity, int YearToDate)
{
int ImportantValue1 = (InputVal * Quantity) + Delta();
int ImportantValue2 = (InputVal * YearToDate) + 100;
if ((YearToDate - ImportantValue1) > 100)
{
ImportantValue2 -= 20;
}
int ImportantValue3 =ImportantValue2 * 7;
return ImportantValue3 - 2 * ImportantValue1;
}
int RefactorMethod::Delta()
{
return 10;
}
修改1:创建新类,所有临时变量改为成员变量,构造函数用来传递原函数参数
修改2:在compute()函数中实现gamma的功能
修改3:修改旧函数,将它的工作委托给新的类对象
修改之后的代码
/////////////////////////.h
class GammaClass
{
public:
GammaClass(RefactorMethod *prm, int InputVal, int Quantity, int YearToDate);
int Compute();
private:
RefactorMethod *m_prm;
int m_InputVal;
int m_Quantity;
int m_YearToDate;
int m_ImportantValue1;
int m_ImportantValue2;
int m_ImportantValue3;
};
/////////////////////////.cpp
int RefactorMethod::Gamma(int InputVal, int Quantity, int YearToDate)
{
GammaClass *pgamma = new GammaClass(this, InputVal, Quantity, YearToDate);
return pgamma->Compute();
}
int RefactorMethod::Delta()
{
return 10;
}
GammaClass::GammaClass(RefactorMethod *prm, int InputVal, int Quantity, int YearToDate)
{
m_prm = prm;
m_InputVal = InputVal;
m_Quantity = Quantity;
m_YearToDate = YearToDate;
}
int GammaClass::Compute()
{
m_ImportantValue1 = (m_InputVal * m_Quantity) + m_prm->Delta();
m_ImportantValue2 = (m_InputVal * m_YearToDate) + 100;
if ((m_YearToDate - m_ImportantValue1) > 100)
{
m_ImportantValue2 -= 20;
}
int ImportantValue3 =m_ImportantValue2 * 7;
return ImportantValue3 - 2 * m_ImportantValue1;
}
针对Compute()还可以继续进行重构。