重构方法

来源:互联网 发布:大唐后妃珍珠传奇 知乎 编辑:程序博客网 时间:2024/05/21 08:44

1.合并条件式

if (date.before (SUMMER_START) || date.after(SUMMER_END))

   charge = a + b;

else

   charge = a;

 

修改为:

 

if (notSummer(date))

   charge = a + b;

else

   charge = a;

 

2.以多态替换条件式

 

#include "stdafx.h"

class Tbird
{
public:
 virtual int getSpeed()
 {
  return 1;
 }
};

class Tmaque : public Tbird
{
public:
  int getSpeed()
 {
  return 10;
 }
};

class Tdayan : public Tbird
{
public:
  int getSpeed()
 {
  return 100;
 }
};

class Tlaoying : public Tbird
{
public:
  int getSpeed()
 {
  return 1000;
 }
};

int getvalue(Tbird *input)
{
 return input->getSpeed();
}

int main(int argc, char* argv[])
{
 Tlaoying Laoying;
 Tmaque    B;
 Tdayan   D;
 Tbird *uu = new Tlaoying();
 int ispeed = getvalue(&Laoying);
 ispeed = uu->getSpeed();
 ispeed = getvalue(&B);
 ispeed = getvalue(&D);

 return 0;
}