【问题标题】:UML: how to implement Association class in JavaUML:如何在 Java 中实现关联类
【发布时间】:2012-11-18 19:29:10
【问题描述】:

我有这个 UML 关联类。注意:横线是实线,竖线是虚线。

 ---------                  ---------
|         |*(a)        *(b)|         |
| CLASS   |________________|  CLASS  |
|STUDENT  |     |          |  COURSE |
 ---------      |           ---------
                |*(c)
          ______|______
         |             |
         |             |
         |  CLASS      |
         | TRANSCRIPT  |
         |_____________|

我理解这种关系,但在将此 UML 实现到代码时遇到了一些问题。我可以将Student 类和Course 类之间的关系实现为代码。这是我的代码:

class Student {
  Vector<Course> b;
}

class Course {
   Vector<Student> a;
}

但是,在Transcript 类,我不太了解如何在代码中使用这个类。它是StudentCourse 两个类的属性吗?所以,如果这是真的,那么代码将是:

class Student {
  Vector<Course> b;
  Vector<Transcript> c;
}

class Course {
  Vector<Student> a;
  Vector<Transcript> c;
}

这是真的吗?如果这是错误的,请教我如何实现这个 UML。

谢谢:)

【问题讨论】:

  • 成绩单真的是一个类的属性吗?我认为每个学生都有一份成绩单,每个成绩单都可以有一个班级向量。

标签: java associations uml


【解决方案1】:

首先,不要使用 Vector,因为它是一个老类,不应该再使用超过 10 年。使用SetList

如果Transcript 类包含有关学生参加课程的方式的信息(例如,其订阅课程的日期),您可以这样实现它:

class Student {
    Set<Transcript> transcripts;
}

class Transcript {
    Student student;
    Course course;
    Date subscriptionDate;
}

class Course {
    Set<Transcript> transcripts;
}

这并不妨碍您在 Student 中提供返回所有课程的方法:

public Set<Course> getCourses() {
    Set<Course> result = new HashSet<Course>();
    for (Transcript transcript : transcripts) {
        result.add(transcript.getCourse());
    }
    return result;
}

如果Transcript 不包含任何信息,那么它可能用于模拟这些类在数据库表中的映射方式,其中在两个表之间建立多对多关联的唯一方法是使用连接包含两个关联表的 ID 的表。

【讨论】:

  • 是否需要双向关联?即是否需要在所有关联情况下添加student in course和course in student?
  • 不,不是。但是 OP 想要这种双向性。
【解决方案2】:

我知道这个问题很老了,但我有一种比在关联类中嵌入 n..1 关系更方便的方法:

public class Transcript {
    //Transcript's properties
} 

public class Course {

    private Map<Student, Transcript> transcriptsByStudent;
}

public class Student {

    private Map<Course, Transcript> transcriptsByCourse;
}

【讨论】:

    【解决方案3】:

    只是补充一下,在您的模型上,您表示关联类的多重性。这是不必要的,因为关联类IS本身就是关联,原来两个类的多重性关系会满足。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多