class EmployeeSalary
{
private double baseSalary = 15000.0;
public double Salary(Employee employee)
{
return baseSalary + 10000 / employee.Level;
}
// other method with baseSalary
}
class Employee
{
public int Level { get; set; }
}
冲动后:
class EmployeeSalary
{
private double baseSalary = 15000.0;
public double Salary(Employee employee)
{
return employee.Salary(baseSalary);
}
// other method with baseSalary
}
class Employee
{
public int Level { get; set; }
public double Salary(double baseSalary)
{
return baseSalary + 10000 / Level;
}
}
2. Move Field (值域搬家)
解释:
有一天发现公司原来计算员工工资的方法不合适了, 比如不是所有的员工起薪 (baseSalary) 都是一万五, 我想把 baseSalary 搬
到 Employee 这个物件中作为员工的一个属性.
这样做可使程序扩展性变得更好, 最明显的是我可以设置不同员工的起薪了.
冲动前:
class EmployeeSalary
{
private double baseSalary = 15000.0;
public double Salary()
{
double salary = baseSalary;
//do some compution with salary
return salary;
}
}
冲动后:
class EmployeeSalary
{
public double Salary(Employee employee)
{
double salary = employee.BaseSalary;
//do some compution with salary
return salary;
}
}
class Employee
{
public double BaseSalary { get; set; }
}
3. Extract Class (提炼类)
解释:
当某个物件做的事情过多, 这样的物件往往含有大量的字段, 属性和方法. 应该由两个或更多个物件来分担这些责任, 这时需要使
用 Extract Class.