Class 场景设计:继承与枚举

Class design for a scenario: inheritance vs enum

我想在 java 代码中表示以下场景:

A professor works in an office and can take a paid leave to carry out some scholarly activities outside of the university. A professor has a title and is enrolled in one department. A professor can be a full professor, an associate professor, or an assistant professor. An assistant professor has a minimum number of courses. Full professors, associate professors, and assistant professors can all take an unpaid leave. The unpaid leave of an assistant professor should not last more than three months.

我已经使用继承来表示 classes:

class Professor {
    String title;
    Department department;
}

class AssociateProfessor extends Professor {
}

class AssistantProfessor extends Professor {
}

class FullProfessor extends Professor{
}

另一种方法是对教授类型使用枚举,例如:

enum professor {full, associate}` 

我不确定哪一个是最好的方法。
在给定的场景中也有一些要求:

  1. 教授可以带薪休假
  2. 助理教授有最低课程数
  3. 一些教授可以休无薪假
  4. 助理教授的无薪假不应超过三个月

我不确定如何在 classes 中表示它们。但是我在这里做了尝试:

class Professor {
    String title;
    Department department;
    int paidLeaves;
}


class AssistantProfessor extends Professor {
    int numOfCourses;
    int unpaidLeaves;

    AssistantProfessor(int _numOfCourses,...) {
        if(_numOfCourses <10)
            throw new Exception("Need a minimum number of courses");
        if(unpaidLeaves >90)
            throw new Exception("...");
    }
}

在上面,我不确定是否应该将带薪或无薪休假视为单独的 class 或接口或枚举,以及是否有更好的方式来表示行 not last more than three months.任何想法都会很棒

你的叙述解释了不同类型的教授具有不同的行为和属性:

  • 候选人 1:一个 «interface» Professor 和三个 classes FullProfessorAssociateProfessorAssistantProfessor每个实现(实现)接口。
    优势:class 设计的总体灵活性。
    不便之处:必须多次重新实现常见行为(否 DRI)。 she/he 更改类别时,教授没有连续性。
  • 候选人 2:一个 class Professor 带有一个枚举 Category,可能取值 FullAssociate,和 Assistant
    优点:class设计简单。
    不便:操作必须实现很多条件语句来实现特定于类别的行为。如果某些类别的教授需要额外的属性,您将为所有人提供它们。更糟糕的是:很难添加新的教授类别,因为您需要更改原来的 class(没有 OCP)。
  • 候选人3:A class Professor专攻三个classes FullProfessor, AssociateProfessor,和 AssistantProfessor
    优点:通用行为只定义一次;每个专业化都可以重新定义一些行为并丰富基础 class。添加新的 class 教授也很容易。
    不便:如果 his/her 类别发生变化,则很难更改 class 教授(尽管这在UML,大多数语言不允许它)。
  • Candidate 4: A class Professor 引用当前 State,并将状态依赖行为转发给状态。 State 的三个特化:StateFullProfessorStateAssociateProfessorStateAssistantProfessor。这是顺便的state design pattern, which prefers composition over inheritance。优点:教授可以在不失去 his/her identity.Also 的连续性的情况下改变类别,对于教授不变的行为和属性与 his/her 期间发生变化的行为和属性之间的关注点是分离的carrer。
    不便之处:稍微复杂一些。
  • Candidate5:一个classProfessor指的是Role(或合同?)的集合。 Role 的三个特化:RoleFullProfessorRoleAssociateProfessorRoleAssistantProfessor。对于每个行为,Professor 都会将该行为转发给它的所有角色。
    优点:可以应付A场的FullProfessor,B场的AssistantProfessor。
    不便:如果不需要的话,可能有点过分了。

当然还有其他候选设计(我至少看到了另外两个)。现在由您来选择最适合您的需求。

在任何这些场景中,您都可以在图表中用约束记录一些额外的约束,例如“持续时间不超过三个月”。 {}

之间的约束可以用自然语言表达