c# - 将 Composition 用于“is – a”关系的问题

标签 c# oop domain-driven-design solid-principles ooad

我正在为人力资源系统开发系统。有会计员工和程序员员工。在加入公司的第一个月,该员工没有任何角色。一名员工可以同时是会计师和程序员。我有一个由以下代码显示的设计。

现在,我需要通过实现新功能来增强系统:

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; }
}

enter image description here

@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"; } }
}

引用

  1. DDD Approach to Access External Information
  2. Prefer composition over inheritance?
  3. Inheritance vs enum properties in the domain model
  4. Entity Framework: Get Subclass objects in Repository

最佳答案

要使用您正在使用的结构,您需要对会计和程序员进行多重继承,此外,新角色可能会添加到系统中,而这在 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/

相关文章:

c# - 为什么在类中使用成员变量

python - 从类中的另一个静态方法函数调用函数

entity-framework - 将 F# 类型保存到数据库

entity-framework - 在领域驱动设计中为模型属性设置默认值的最佳实践?

domain-driven-design - DDD 不变量业务规则和验证

c# - 如果集合为空,如何返回默认值?

c# - await 不会在原始上下文中恢复

c# - Windows 任务栏中不显示应用程序标题

c# - 如何将这几天转换为位掩码?

java - 解析数据字符串的正确方法