《重构:改善既有代码的设计》 重新组织数据 之 1

版权声明:请注明转发出处 https://blog.csdn.net/mafucun1988/article/details/89412542

《重构:改善既有代码的设计》中提到过很多重构方法,关于重新组织数据的方法有8种。本文介绍:
自封装字段 self encapsulate field

  • 名称:自封装字段 self encapsulate field
  • 概要:为该字段建立取值/设值函数,并且只以这些函数来访问字段
  • 动机: 直接访问一个字段,但与字段之间的耦合关系逐渐变的笨拙。完成自我封装后,可以在子类中根据自己的需要随意覆写取值/设值函数。
  • 做法:
    • 为待封装字段建立取值/设值函数
    • 找出该字段的所有引用点,将它们全部改写为调用取值/设值函数
    • 将该字段声明为private
    • 复查,确保找出所有的引用点
    • 编译,测试
  • 代码演示

修改之前的代码:

///////////////////////////.h
#ifndef REFACTORDATA_H
#define REFACTORDATA_H


class IntRange
{
public:
    IntRange(int low, int high);
    bool includes(int arg);
    void grow(int factor);
private:
    int m_low;
    int m_high;
};

#endif // REFACTORDATA_H
///////////////////////////.cpp
#include "RefactorData.h"


IntRange::IntRange(int low, int high)
{
    m_low = low;
    m_high = high;
}

bool IntRange::includes(int arg)
{
    return arg >= m_low && arg <= m_high;
}

void IntRange::grow(int factor)
{
    m_high *= factor;
}

1)为m_low和m_high设置取值/设值函数,并使用它们
2)一般来说,设值函数应该在对象创建后才使用。可以在构造函数中使用初始化列表,也可以另建一个初始化函数。
3)在子类cappedRange中覆写getHigh(),从而加入对“范围上限” (cap)的考虑,而不必修改IntRange的任何行为。
修改之后的代码:

///////////////////////////.h
#ifndef REFACTORDATA_H
#define REFACTORDATA_H


class IntRange
{
public:
    IntRange(int low, int high);
    bool includes(int arg);
    void grow(int factor);
    int getHigh() const;
    void setHigh(int high);
    void initialize(int low, int high);

    int getLow() const;
    void setLow(int low);

private:
    int m_low;
    int m_high;
};


class CappedRange : public IntRange
{
public:
    CappedRange(int low, int high, int cap);
    int getCap() const;
    void setCap(int cap);
    int getHigh() const;

private:
    int m_cap;
};

#endif // REFACTORDATA_H

///////////////////////////.cpp
#include "RefactorData.h"


IntRange::IntRange(int low, int high) : m_low(low), m_high(high)//初始化列表
{
    //初始化函数
    //initialize(low, high);
}

bool IntRange::includes(int arg)
{
    return arg >= getLow() && arg <= getHigh();
}

void IntRange::grow(int factor)
{
    setHigh(getHigh() * factor);
}

int IntRange::getHigh() const
{
    return m_high;
}

void IntRange::setHigh(int high)
{
    m_high = high;
}

void IntRange::initialize(int low, int high)
{
    m_high = high;
    m_low = low;
}

int IntRange::getLow() const
{
    return m_low;
}

void IntRange::setLow(int low)
{
    m_low = low;
}

CappedRange::CappedRange(int low, int high, int cap) : IntRange (low,high), m_cap(cap)
{

}

int CappedRange::getCap() const
{
    return m_cap;
}

void CappedRange::setCap(int cap)
{
    m_cap = cap;
}

int CappedRange::getHigh() const
{
    return (getHigh() < getCap() ? getHigh() : getCap() );
}


 

猜你喜欢

转载自blog.csdn.net/mafucun1988/article/details/89412542