重构对象列表以实现业务规则
|
我需要重构以下类:
public interface IEmployee
{
int VacationWeeks { get; }
int YearsWithCompany { set; get; }
double Salary { set; get; }
}
public class Employee : IEmployee
{
private readonly int vacationWeeks;
public Employee(int vacationWeeks)
{
this.vacationWeeks = vacationWeeks;
}
public int VacationWeeks
{
get { return vacationWeeks; }
}
public int YearsWithCompany { set; get; }
public double Salary { set; get; }
}
我需要确保VacationWeeks仅取决于YearsWithCompany,并且正在从数据库加载映射。到目前为止,我已经提出了:
public class EmployeeNew : IEmployee
{
private Dictionary<int,int> vacationWeeksTable;
public EmployeeNew(Dictionary<int, int> vacationWeeksTable)
{
this.vacationWeeksTable = vacationWeeksTable;
}
public int VacationWeeks
{
get { return vacationWeeksTable[YearsWithCompany]; }
}
public int YearsWithCompany { set; get; }
public double Salary { set; get; }
}
此类实现了我想要的功能,但仍然存在一个漏洞:可能已使用VacationWeeksTable的不同实例创建了同一集合中EmployeeNew的不同实例。
同一集合中EmployeeNew的所有实例必须引用相同的VacationWeeksTable。
我重构的应用程序在整个系统中使用了很多List,我们需要能够修改YearsWithCompany和Salary,但要保证每个List仅使用一个VacationWeeksTable。这些列表被迭代了几次;它的元素在每次迭代中都会修改。
这是我不完善的解决方案。欢迎提出建议:
// this class does two things, which I do not like
public class EmployeeList : IEnumerable<IEmployee>, IEmployee
{
private Dictionary<int, int> vacationWeeksTable;
private List<EmployeeSpecificData> employees;
private int currentIndex;
private EmployeeSpecificData CurrentEmployee
{
get { return employees[currentIndex]; }
}
public IEnumerator<IEmployee> GetEnumerator()
{
for (currentIndex = 0; currentIndex < employees.Count; currentIndex++)
{
yield return this;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int VacationWeeks
{
get { return vacationWeeksTable[YearsWithCompany]; }
}
// this is ugly repetitive code I don\'t like
public int YearsWithCompany
{
get { return CurrentEmployee.YearsWithCompany; }
set { CurrentEmployee.YearsWithCompany = value; }
}
// this is ugly repetitive code I don\'t like
public double Salary
{
get { return CurrentEmployee.Salary; }
set { CurrentEmployee.Salary = value; }
}
}
没有找到相关结果
已邀请:
2 个回复
磐乓铝举
每当您创建Employee类时:
它仅对类使用WeakReference,因此您不必担心GC。 每位员工将在创建时拥有共享的VacationWeeksTable设置,如果不使用工厂类,则无法从外部进行更改。 您可以在应用程序的运行时随时更改Employee所有正在运行的实例的假期表,方法是:
员工实施示例:
代码模式实现: IBaseClass:我可以通过工厂实现创建的每个类的接口
实用程序通用类:
工厂类进行了一些修改以处理您的情况:
妊辽剁茧