我正在为人力资源系统开发系统。有会计员工和程序员员工。在加入公司的第一个月,该员工没有任何角色。一名员工可以同时是会计师和程序员。我有一个由以下代码显示的设计。
现在,我需要通过实现新功能来增强系统:
Terminate all Accountants. (Terminate means set status of employee as IsActive = false). The issue is I cannot set all accountants directly as inactive without checking. I need to check whether he has got any other role.
如何重构这些类以使终止函数更自然 OO ?
更新
我正在为 @AlexDev 答案寻找具有 EF 数据库优先解决方案模型和数据库架构的答案。
C#代码
List<Accountant> allAccountants = Get All accountants from database
public class Employee
{
public int EmpID { get; set; }
public DateTime JoinedDate { get; set; }
public int Salary { get; set; }
public bool IsActive { get; set; }
}
public class Accountant : Employee
{
public Employee EmployeeData { get; set; }
}
public class Programmer : Employee
{
public Employee EmployeeData { get; set; }
}
@AlexDev 回答
public class Employee
{
...
IList<Role> Roles;
bool isActive;
public void TerminateRole(Role role)
{
Roles.Remove(role);
if(Roles.Count == 0)
{
isActive = false;
}
}
}
public class Role
{
abstract string Name { get;}
}
public class ProgrammerRole : Role
{
override string Name { get { return "Programmer"; } }
}
引用
最佳答案
要使用您正在使用的结构,您需要对会计和程序员进行多重继承,此外,新角色可能会添加到系统中,而这在 C# 中不存在。您应该考虑不同的设计。一种可能:
public class Employee
{
...
IList<Role> Roles;
bool isActive;
public void TerminateRole(Role role)
{
Roles.Remove(role);
if(Roles.Count == 0)
{
isActive = false;
}
}
}
public class Role
{
abstract string Name { get;}
}
public class ProgrammerRole : Role
{
override string Name { get { return "Programmer"; } }
}
然后您可以为每种类型创建 Role 的子类,您可以决定只终止一个角色或所有角色。
关于c# - 将 Composition 用于“is – a”关系的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11759120/